2011-01-27 74 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