I''m creating a address book. A user can have many contacts. In the user model, I put: has_many :contacts And in the contact model, I put: belongs_to :user To list all contacts, I search as following: @user = User.find(session[:user_id]) And rendering: <%= render(:partial => "contact", :collection => @user.contacts)%> To persist I am using the following code: @contact = Contact.new(params[:contact]) @contact.user_id = session[:user_id] @contact.save It works, but is it the best solution? Thanks in advance. Fernando Lujan
Fernando Lujan wrote:> To persist I am using the following code: > > @contact = Contact.new(params[:contact]) > @contact.user_id = session[:user_id] > @contact.saveYou can simplify this bit to: @contact = Contact.new(params[:contact]) @user.contacts << @contact Adding the contact to the collection assigns the foreign key and saves the record. Alternatively, you can use the build method: @contact = @user.contacts.build(params[:contact]) @contact.save -- Philip Ross http://tzinfo.rubyforge.org/ -- DST-aware timezone library for Ruby
Philip Ross wrote:> Fernando Lujan wrote: >> To persist I am using the following code: >> >> @contact = Contact.new(params[:contact]) >> @contact.user_id = session[:user_id] >> @contact.save > > You can simplify this bit to: > > @contact = Contact.new(params[:contact]) > @user.contacts << @contact > > Adding the contact to the collection assigns the foreign key and saves > the record. > > Alternatively, you can use the build method: > > @contact = @user.contacts.build(params[:contact]) > @contact.saveThanks Philip, but using this code I will have to search the user, right? @user = User.find(session[:user_id] @contact = Contact.new(params[:contact]) @user.contacts << @contact Correct?
Fernando Lujan wrote:> Thanks Philip, but using this code I will have to search the user, right? > > @user = User.find(session[:user_id] > @contact = Contact.new(params[:contact]) > @user.contacts << @contact > > Correct?Yes, that is correct. -- Philip Ross http://tzinfo.rubyforge.org/ -- DST-aware timezone library for Ruby