Jonathan Jonathan - 1 year ago 64
Ruby Question

Listing all posts from a certain category

I currently have a posts model which has a category:string column on it. I'm looking to display all posts in certain categories.

e.g. On click of 'Technology' category link - load all posts which have apple as the category.

Couldn't find anything on stack overflow on this, but I may be looking for the wrong thing. Any help would be brilliant and appreciated!


Answer Source

Post.where(category: 'Animals')

would return all posts with specified category.

As to comments under the question - yeah, you can benefit from having additional model Category, because post can have more, than one category.

You would define the relation as one of the following:

  1. HBTM

    has_and_belongs_to_many :categories # post.rb has_and_belongs_to_many :posts # category.rb

  2. has_many through


has_many :categories_posts
has_many :categories, through: :categories_posts


has_many :categories_posts
has_many :posts, through: :categories_posts


belongs_to :category
belongs_to :post


to add selecting category(ies) to form, add the following to it (assuming Category has name attributes):

<%= :categories, Category.pluck(:id, :name), {}, multiple: true %>

Also don't forget to whitelist categories in permitted params (posts_controller.rb):

def post_params
  params.require(:post).permit(:attr1, :attr2, category_ids: [])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download