简体   繁体   中英

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

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
Article.joins(:category).where(categories: {id: :your_category_id})
#config/routes.rb
resources :articles do
   get ":category_id", action: :index, on: :collection #-> url.com/articles/:category_id
end

#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
   def index
      if params[:category_id]
         @articles = Article.joins(:categories).where(category: {id: params[:category_id]})
      else
         @articles = Article.all
      end
   end
end

This will allow you to use:

#app/views/articles/index.html.erb
<%= form_tag articles_path do %>
    <%= f.collection_select :category_id, Category.all, :id, :name %>
    <%= f.submit %>
<% end %>
<% @articles.each do |article| %>
   <%= article.title %>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM