The Definitive Guide to accepts_nested_attributes_for a model in rails 3

Experience Satire

accepts_nested_attributes_for is very useful when you want a single form to cater to multiple models. It gives you an easy way to include attributes from the associated tables and also to successfully save and delete objects.

Consider a scenario where ‘House’ has many ‘Rooms’  and has one ‘Address’. It also belongs to an ‘Owner’. Now suppose you want a single form for house which is able to present attributes for room[size], address[city,country] and user[fname,lname] and also is able to save it successfully. It entails the following steps.

1. In model house.rb

2. In house_controller.rb you need to build the attributes. Notice the different methods used to build different associated models. It is a function of whether House has one or many of the other model. (Belongs to is a ‘one’ association). Also, I am only showing the parts which needs deviation from the general scaffolded code.

3. In view i.e…

View original post 18 more words

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s