Has_many association

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 L.

Fernando L. 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.save


Philip R.
http://tzinfo.rubyforge.org/ – DST-aware timezone library for Ruby

Fernando L. 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 R.
http://tzinfo.rubyforge.org/ – DST-aware timezone library for Ruby

Philip R. wrote:

@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

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?