Mongoid Relational Associations
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 :use开发者_运维技巧rname
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
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.
精彩评论