2016-12-25 58 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 }