Skip to content

Instantly share code, notes, and snippets.

@tkbeili
Created March 25, 2013 16:11
Show Gist options
  • Select an option

  • Save tkbeili/5238275 to your computer and use it in GitHub Desktop.

Select an option

Save tkbeili/5238275 to your computer and use it in GitHub Desktop.
Steps for creating one to many relationship with SQL database in Rails
1- Decide which one is the “parent” and which one is the “child”. So the parent has_many children
2- If you are using SQL database add a column to the child ActiveRecord model named parent_id
3- In the parent ActiveRecord model add has_many :children (notice we used plural in here)
4- In the child ActiveRecord model add belongs_to :parent (notice we used singular in here)
5- (optional) Change the child controller to be nested from the parent’s controller in order to re-use methods (mostly for before_filter) by:
a- Makes the routes for the child controller nested inside the “show” action of parent controller
b- Make the child controller inherit from the parent controller.
c- Setup filters as needed
d- Change URLs relating to child controller around your app.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment