Alex Nikolsky
Alex Nikolsky

Reputation: 2179

How to filter resources in Rails?

Currently, I'm building a blog in Rails and I am being curious is there a right way to display resources in the following manner?

enter image description here

In this case you may be able to list all the posts, and if needed, separate category posts.

You'd normally say - use scopes, however I'm not sure scopes are gonna produce the following adressess: /blog/features, /blog/releases.

So, how can I do this?

Upvotes: 2

Views: 512

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

#config/routes.rb
resources :blogs, path: "blog" do 
   get ":category", to: :index, on: :collection #-> url.com/blog/:category
end

#app/controllers/blogs_controller.rb
class BlogsController < ApplicationController
   def index
       @posts = params[:category] ? Post.joins(:category).where(category: {name: params[:category]}) : Post.all
   end
end

#app/views/posts/index.html.erb
<% @posts.each do |post| %>
   ...
<% end %>

Upvotes: 2

Related Questions