2016-12-25 62 views
0

我有2個不同的index行動,任何人都可以幫我合併嗎?如何合併這兩個def索引

首先高清指數(用於標籤):

def index 
    if params[:tag] 
    @posts = Post.tagged_with(params[:tag]) 
    else 
    @posts = Post.all 
    end 
end 

二高清指數(用於類):

def index 
    if params[:category].blank? 
    @posts = Post.all 
    else 
    @category_id = Category.find_by(name: params[:category]).id 
    @posts = Post.where(category_id: @category_id) 
    end 
end 

回答

0

像這樣的事情會做

def index 
    if params[:tag].present? 
    @posts = Post.tagged_with(params[:tag]) 
    elsif params[:category].present? 
    @category = Category.find_by_name(params[:category]) 
    @posts = @category.posts  
    else 
    @posts = Post.all 
    end 
end 
+0

謝謝。其作品。 – Fahad

0

下面是一個簡短的版本:

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 }