Skip to content

Instantly share code, notes, and snippets.

@poc7667
Last active December 20, 2015 07:59
Show Gist options
  • Select an option

  • Save poc7667/6097512 to your computer and use it in GitHub Desktop.

Select an option

Save poc7667/6097512 to your computer and use it in GitHub Desktop.
class Categorization < ActiveRecord::Base
attr_accessible :category_id, :product_id
belongs_to :product
belongs_to :category
end
class Category < ActiveRecord::Base
attr_accessible :name
has_many :categorizations
has_many :products, :through => :categorizations
end
class Product < ActiveRecord::Base
attr_accessible :name
has_many :categorizations
has_many :categories, :through => :categorizations
end
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% @categories.each do |category| %>
<%= category.name %>
<%= check_box_tag "categories_names[]", category.name %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
# POST /products.json
def create
@product = Product.new(params[:product])
if @product.save
params[:categories_names].each do |item|
add_category_tag = Category.where(:name => item)
@product.categories << add_category_tag
end
end
class CreateCategoriesProductsJoin < ActiveRecord::Migration
def up
create_table 'categories_products', :id => false do |t|
t.column 'category_id', :integer
t.column 'product_id', :integer
end
end
def down
drop_table 'categories_products'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment