Skip to content

Instantly share code, notes, and snippets.

@jwoertink
Created June 18, 2014 19:15
Show Gist options
  • Select an option

  • Save jwoertink/c75b4fa226e9ccee84a3 to your computer and use it in GitHub Desktop.

Select an option

Save jwoertink/c75b4fa226e9ccee84a3 to your computer and use it in GitHub Desktop.
Understanding Associations in rails
1. Take 2 models
2. Associate them
3. Ensure database has association columns needed
4. Scope routes
5. Use the scope in your controller
Example:
class Meat
belongs_to :sandwhich
end
class Sandwhich
has_many :meats
end
$ rails g migration add_sandwhich_id_to_meats sandwhich_id:integer
resources :sandwhiches do
resources :meats
end
class MeatsController
before_action :find_sandwhich
private
def find_sandwhich
@sandwhich = Sandwhich.find(params[:sandwhich_id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment