Forum: Ruby on Rails has_many association.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fernando L. (Guest)
on 2006-05-10 22:42
(Received via mailing list)
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.
Philip R. (Guest)
on 2006-05-11 03:28
(Received via mailing list)
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. (Guest)
on 2006-05-11 17:14
(Received via mailing list)
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?
Philip R. (Guest)
on 2006-05-11 23:50
(Received via mailing list)
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
This topic is locked and can not be replied to.