Mongoid 关系关联

发布于 2024-10-14 11:39:01 字数 976 浏览 3 评论 0原文

我正在使用rails3+mongoid+devise来创建应用程序。我有用户,每个用户都可以有约会,我想知道我是否应该在约会文档中显式存储 user_id 或如何让 mongoid 通过定义的关系自动处理这个问题。

用户和约会模型如下

class User
  include Mongoid::Document
  devise: database_authenticable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  field :username
  validates_presence_of :username
  validates_uniqueness_of :name, :email, :case_sensitive => false
  attr_accessible :name, :email, :password, :password_confirmation

  references_many :appointments
end

class Appointment
  include Mongoid::Document

  field :date, :type => Date, :default => Date.today
  referenced_in :user
end

我想知道如何创建约会并将其与当前登录的用户(使用设备的 current_user )相关联。

对以下锻炼控制器有什么建议,特别是第 2 行?

def create
  @appointment = current_user.Appointment.new(params[:appointment])
  if @appointment.save
    redirect_to(:action => 'show', :id => @appointment._id)
  else
    render('edit')
  end
end

I am using rails3+mongoid+devise to create an application. I have users, and each user can have appontments, I am wondering if i should explicitly store a user_id in the appointment document or how to get mongoid to handle this automatically with the defined relationship.

The User and Appointment models are as follows

class User
  include Mongoid::Document
  devise: database_authenticable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  field :username
  validates_presence_of :username
  validates_uniqueness_of :name, :email, :case_sensitive => false
  attr_accessible :name, :email, :password, :password_confirmation

  references_many :appointments
end

class Appointment
  include Mongoid::Document

  field :date, :type => Date, :default => Date.today
  referenced_in :user
end

I am wondering how to go about creating the appointment and having it associated with the current logged in user (current_user using devise).

Any advice on the following workout_controller, specifically line 2?

def create
  @appointment = current_user.Appointment.new(params[:appointment])
  if @appointment.save
    redirect_to(:action => 'show', :id => @appointment._id)
  else
    render('edit')
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静赏你的温柔 2024-10-21 11:39:01

首先,我相信 Appointment 类的最后一行应该是 referenced_in :user 而不是 :person

然后,您应该能够按如下方式修复控制器的第 2 行:

@appointment = current_user.appointments.new(params[:appointment])

保存后,current_user.appointments 应包含新约会。

First off, I believe your last line of the Appointment class should say referenced_in :user instead of :person.

Then, you should be able to fix line 2 of your controller as follows:

@appointment = current_user.appointments.new(params[:appointment])

After saving it, current_user.appointments should include the new appointment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文