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.
88ade3846f380b12dc27cada47138661?d=identicon&s=25 Fernando Lujan (Guest)
on 2006-05-10 20: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 Lujan
9ab183bb240ffd3a3966d5a615b4bdeb?d=identicon&s=25 Philip Ross (Guest)
on 2006-05-11 01:28
(Received via mailing list)
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.save

--
Philip Ross
http://tzinfo.rubyforge.org/ -- DST-aware timezone library for Ruby
88ade3846f380b12dc27cada47138661?d=identicon&s=25 Fernando Lujan (Guest)
on 2006-05-11 15:14
(Received via mailing list)
Philip Ross 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?
9ab183bb240ffd3a3966d5a615b4bdeb?d=identicon&s=25 Philip Ross (Guest)
on 2006-05-11 21:50
(Received via mailing list)
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
This topic is locked and can not be replied to.