Mongoid 关系关联
我正在使用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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我相信
Appointment
类的最后一行应该是referenced_in :user
而不是:person
。然后,您应该能够按如下方式修复控制器的第 2 行:
保存后,
current_user.appointments
应包含新约会。First off, I believe your last line of the
Appointment
class should sayreferenced_in :user
instead of:person
.Then, you should be able to fix line 2 of your controller as follows:
After saving it,
current_user.appointments
should include the new appointment.