Search code examples
ruby-on-railsrubyhas-and-belongs-to-many

How to show articles with special categories?


So I'm using has_and_belong_to_many association for two models (Article and Category). My header have link with dropdown menu where different categories appears. All my articles are on index page and I need to sort it depending what category it has so users could choose what they want to see. I guess I should do something in show action in category controller, but don't know what exactly. To solve this I played with different each iterations in my views and controller, but unfortunately it didn't help.

Any help will be appreciated


Solution

  • You can select articles with certain category with

    selected_articles = Category.find_by_name("Name of category").articles
    

    Or, if you don't know the name simply

    selected_articles = Category.find(category_id).articles