Adding categories to a Ruby on Rails application
I've had some issues with this before when creating applications and I think I'm starting to run into it again, hence I'm asking this on StackOverflow to save me a lot of time. I've spent the last few weeks setting up a perfected product model for my system. The model performs exactly as I want it to and has several complex features (such as search via sunspot). I wanted to setup the category to product structure before I started this heavy development - however struggling with thi开发者_JAVA技巧s kind of thing was just putting me off creating the application so I got straight into the product structure. Now I've got the product model setup - what would be the easiest way to add a category ownership to encompass the products? (All products have a category_id column which store their father category id) My plan is to have the category index to be a list of all the categories, the category show to be a list of the products inside that category and the product show being the view of the actual product. This would eliminate the product index and so I'll have to come up with a way to port the search feature (sunspot) from my index view to the category show somehow. As for the actual listing of the products - I assume I'll have to do some kind of partial? (I don't know a lot about it).
Most basically, my relationships are planned to be: category:
has_many :products
product:
has_one :category
My products then have a category_id column to store the ID of it's parent category.
Any tips on how to accomplish the relationships (category show to list the products etc)?
Best Regards,
Joe
Relationships like the one you're wanting are built into ActiveRecord support. Understanding the model relationships in Rails is critical to doing anything in Rails that's non-trivial, so study up.
Also, the relationship you're looking for is something like:
product:
belongs_to :category
category:
has_many :products
精彩评论