2011-01-27 75 views
0

我正在使用rails3 + mongoid + devise来创建应用程序。我有用户,每个用户可以有appontments,我想知道如果我应该明确存储user_id在约会文档或如何让mongoid自动处理这与定义的关系。Mongoid Relationships Associations

用户和预约型号如下

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),具有其与登录用户当前相关。

有关以下workout_controller的任何建议,特别是第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 

回答

1

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

然后,你应该能够解决您的控制器的线2如下:

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

保存之后,current_user.appointments应包括新的任命。

+0

糟糕,这个:而不是:用户是我的一个错字。但是,是的,它现在很有用,很棒。忘记了您需要使用“appointments.new”而不是“appointment.new” – Hutch 2011-01-27 04:06:35