Reputation: 67
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
end
and table
product_category with product_id and category_id
, it working good then i put data to it, but how i need to get data for example by category? category_id = 1 and all products by this category
Thank you
Upvotes: 2
Views: 2980
Reputation: 2244
your join table needs be called categories_products thats the rails default for the join table name, it is in alphabetical order so categories before products and they need to be plural.
once you have that working you can access the association by name like a method:
Category.find(1).products
gives you all products belonging to category of id 1
Product.find(1).categories
gives you all categories belonging to product of id 1
and so on...
Upvotes: 4
Reputation: 1
Try this...once you change the join table to categories_products.
<% category.products.each do |product| %>
<td><%= product.name %></td>
<% end %>
..............
define the scope in your model scope :sorted, order('products.name ASC')
and the @products = Products.sorted
in your controller.
That said I would recommend trying the has_many products :through => categorization
That should do the trick.
Upvotes: 0