I am new to Ruby and Rails so bear with me please. I have created a very simple blog application with both posts and comments. Everything works great. My next question regarding adding categories. I am wondering the best way to do this. As I can't see too far in front of me yet when it comes to Rails I thought I would ask.
To be clear, I would like that a single post can have multiple categories and a category can have multiple posts.
Is the best way to do this to create a 'categories' table and then use the posts and categories models to do has_many :posts
, has_many :categories
? Would I also then set the routes.rb
such that posts are embedded under categories?
Or is there an easier way by simply adding a category column to the existing posts table? (in which case I would imagine having multiple categories woul开发者_运维技巧d be difficult).
It depends how much effort you're willing to put in - you could use a tagging plugin, or set up a has_and_belongs_to_many
relationship in both the Posts and Categories models, but I'd recommend something a bit different.
If you create a third model, "Categorizations", as a kind of "glue" beween Posts and Categories, you can have more control. Post has_many :categories :through => categorizations
and Category has_many :posts :through => :categorizations
A benefit of this is that your categories aren't stored in your code, but rather in the database - so adding/removing/editing them doesn't require you to modify any source code. How you set up the routes is completely up to you - you could have /categories/:id
return a list of all posts that belong to that category, or implement some kind of search form using one or more categories as parameters.
Ryan Bates has an excellent screencast explaining all of this, with several different ways of tackling the problem.
I know you mentioned you're new to RoR, so I apologise if this is a little complicated for what you want. As I said, a plugin might be best for your needs, but I find it's always nice to have coded it yourself if possible, with the added benefit of having more flexibility and control :)
Since you want a many-to-many relationship between categories and posts, I would (and do) use a tagging plugin such as ActsAsTaggableOn, where you can define what a "tag" is referred to, and call it "category." Simple and effective. In your form, you can limit the possible values for a "tag" with a whitelist (like, "coding," "recipes," "vacation") for your different categories.
精彩评论