Associations

9 views
Skip to first unread message

Avi

unread,
Dec 11, 2012, 4:49:09 AM12/11/12
to rubyonra...@googlegroups.com
Hello,

If user --> has_many :address

How can we do a build_address as it expects a has_one relationship?


Thanks,
Avi

Colin Law

unread,
Dec 11, 2012, 4:56:29 AM12/11/12
to rubyonra...@googlegroups.com
@user.addresses.build( ... )

Have a look at the Rails Guide on ActiveRecord Associations. It shows
all the methods available for each association type.

Colin

Bala Mani

unread,
Dec 11, 2012, 7:25:42 AM12/11/12
to rubyonra...@googlegroups.com
Hai!

View this link

      http://guides.rubyonrails.org/association_basics.html


by
bdeveloper01

Jordon Bedwell

unread,
Dec 11, 2012, 9:24:34 AM12/11/12
to rubyonra...@googlegroups.com
On Tue, Dec 11, 2012 at 3:49 AM, Avi <aavinas...@gmail.com> wrote:
> If user --> has_many :address
>
> How can we do a build_address as it expects a has_one relationship?

The association is created by a foreign key on addresses which should
be `user_id` unless you want a custom field (for example I would
prefer it to be uid so I tell them that is the case but you need to
read the links provided by others to see how to do that.) Then to the
easiest way to create records on the association is:

User.find_by_email("na...@example.com").addresses.new

Though again, for the sake of context and readability I prefer to also
alias all my associations to their singular form for creation because
to me it makes no sense to do User.new.addresses.new when you are only
creating a single address, it only makes sense when pulling the them.
Reply all
Reply to author
Forward
0 new messages