I am trying to get my head around how to deal with my Products <-> Categories relation. I am trying to build a small shop in rails and I want to make a navigation out of the category tree.
The navigation will look something like this:
- Men
|--Shirts
|--Pants
- Woman
|--Shirts
|--Dresses
-Accessoires
You get the idea...
Now, the problem is that these appear to be all different scopes on the same model, Product, with different find conditions on the associated Category.
My models so far:
class Product < ActiveRecord::Base
# validations...
has_many :categorizations
has_many :categories, :through => :categorizations
# more stuff ...
end
class Category < ActiveRecord::Base
acts_as_nested_set
has_many :categorizations
has_many :products, :through => :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :c开发者_如何学运维ategory
end
Also, I want to have multiple categories on my products and maybe make it possible to create new categories "on-the-fly" when adding a product. So the whole category management should be as easy as possible. If someone can point me in the right direction or link me to a tutorial, best practice or anything would be really awesome!
UPDATE
Ok, so now I can creating categories on the fly using virtual attributes, the question is how do I search for articles of a specific category?
What I tried:
@products = Product.scoped(:include => :categorizations, :conditions => {:category_names => params[:category]})
or
@products = Product.where("categorization = ?", params[:category])
but both didnt work. basically i want all products of one category...
You can allow users to create new categories at the same time as creating new products by using accepts_nested_attributes_for
in your model. Have a look through the documentation for that to get you started.
So I ended up creating a many-to-many relation through categorizations. This railscast explains perfectly how to do this and create new categories (or tags) on-the-fly.
After I loop through the categories to make them links in my product overview:
# app/views/products/index.html.erb
<ul class="categories">
<% for category in @categories %>
<li><%= link_to category.name, :action => "index" , :category => category.id %></li>
<% end %>
</ul>
and then in the controller I build the products from the category if there is any:
# products_controller.rb
def index
if params[:category]
@products = Category.find(params[:category]).products
else
@products = Product.scoped
end
@products = @products.where("title like ?", "%" + params[:title] + "%") if params[:title]
@products = @products.order('title').page(params[:page]).per( params[:per_page] ? params[:per_page] : 25)
@categories = Category.all
end
for sure there is a more elegant way to do it but this wors for now.. any improvement appreciated.
精彩评论