Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Ryan Trimble
Ryan Trimble
15,559 Points

Rails Model Association Question....

Looking for a guide or assistance on how to do something in Ruby on Rails.

I have two models, "Restaurants" and "Menus" which are associated. Restaurants has_many Menus and Menu belongs_to Restaurant. These are working properly, as I can reference each from the other, however I'm not quite sure how to go about creating them properly.

Right now I can create a new Menu and tell it a restaurants ID to associate that menu to a restaurant, but it would be much better if I could select the restaurant first, then the menu would automatically know which restaurant to associate it with. Something like on the restaurant's show page it would have a link that says "Create New Menu" and clicking that link would load the menu create form, but it would already know which Restaurant the menu should belong to.

Hopefully this makes sense!!

Any assistance would be great!

1 Answer

Pedro Henrique Knoll Giacometo
Pedro Henrique Knoll Giacometo
6,669 Points

Ryan,

It's difficult to answer without understand more your goals.

But a good start is to search for accepts_nested_attributes_for at the rails api.

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Then you can watch the railscast about how to setup the forms.

https://www.youtube.com/watch?v=a61yKxi3pL0