Rails : Associating has_many relationships

bootstrap has_many associationproduct category model has_many association

we’ll start with a new App and we’ll generate a scaffold product model and category model, following this bellow:

rails g scaffold Product name:string price:decimal
rails g scaffold Category name:string
rails g migration add_category_id_to_products category_id:integer

don’t forget

rake db:migrate

in category model

class Category < ActiveRecord::Base
  has_many :product
  attr_accessible :name
end

next in Product Model

class Product < ActiveRecord::Base
  belongs_to :category
  attr_accessible :name, :price, :category_id
end

finally, edit your code in app/views/product model, in index.html.erb and show.html.erb

<%= @product.category_id %>

which become

<%= @product.category.name %>

and specially
_form.html.erb

<div class="control-group">
      <%= f.label :category_id, :class => 'control-label' %>
      <div class="controls">
        <%= f.collection_select :category_id, Category.all, :id, :name %>
     
      </div>
    </div>
Advertisements

2 thoughts on “Rails : Associating has_many relationships

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