ruby on rails - Listing all posts from a certain category -
i have posts model has category:string column on it. i'm looking display posts in categories.
e.g. on click of 'technology' category link - load posts have apple category.
couldn't find on stack overflow on this, may looking wrong thing. brilliant , appreciated!
thanks
post.where(category: 'animals')
would return posts specified category.
as comments under question - yeah, can benefit having additional model category
, because post can have more, 1 category.
you define relation 1 of following:
hbtm
has_and_belongs_to_many :categories # post.rb has_and_belongs_to_many :posts # category.rb
has_many through
post.rb
has_many :categories_posts has_many :categories, through: :categories_posts
category.rb
has_many :categories_posts has_many :posts, through: :categories_posts
categories_posts.rb
belongs_to :category belongs_to :post
edit
to add selecting category(ies) form, add following (assuming category
has name
attributes):
<%= f.select :categories, category.pluck(:id, :name), {}, multiple: true %>
also don't forget whitelist categories in permitted params (posts_controller.rb
):
def post_params params.require(:post).permit(:attr1, :attr2, category_ids: []) end
Comments
Post a Comment