下面是一個簡短的版本:
def index
@posts =
if params.key?(:tag)
Post.tagged_with(params[:tag])
elsif params.key?(:category)
Post.joins(:categories).where(categories: { name: params[:category] })
else
Post.all
end
end
不過,我不知道如果這種情況確實值得三個不同的途徑和控制器:
# config/routes.rb
resources :categories, only: [] { resources :posts, only: :index }
resources :tags, only: [] { resources :posts, only: :index }
resources :posts, only: :index
那麼
# categories_posts_controller.rb
class CategoriesPostsController < ApplicationController
def index
@posts = Post.joins(:categories).where(categories: { id: params[:category_id] })
end
end
等等:
# tags_posts_controller.rb
class TagsPostsController < ApplicationController
def index
@posts = Post.tagged_with(params[:tag_id])
end
end
如果您還沒有一個id
可以使用,則可以在路徑改變帕拉姆名稱是任何你想要的。
resources :categories, only: [] { resources :posts, only: :index, param: :name }
謝謝。其作品。 – Fahad