2014-02-23 47 views
0

我将过滤功能放入应用程序(Rails 4.1beta) - 我通过在Item模型上创建作用域,通过请求参数传递作用域并在索引行动。这一切都有效,但是我试图摆脱其中一个控制器的索引操作中的代码味道;减少轨道控制器中的作用域过滤器

def index      
    case params[:scope]   
    when "recent"    
     @items = Item.recent 
    when "active" 
     @items = Item.active 
    when "inactive" 
     @items = Item.inactive 
    else 
     @items = Item.all 
    end 
end 

这一切都觉得有点过于僵硬/冗长。我真的很想做这样的事情;

def index 
    @items = Item.send(params[:scope]) 
end 

但是随后我将应用程序全部公开给调用Item类的方法的人。在那里的打击条件有点击败了我想要实现的目标。

是否有一些轨道魔法我错过了,可以帮助我吗?

回答

1

您可以使用不同的控制器来完成其中的每一个。

inactive_items_controller.rb

def index 
    @items = Item.inactive 
end 

recent_items_controller.rb

def index 
    @items = Item.recent 
end 

或者你可以打动你,你有上面的模型

项目模型

逻辑
def self.custom_scope(scope) 
    case scope 
    when "recent"    
    Item.recent 
    when "active" 
    Item.active 
    when "inactive" 
    Item.inactive 
    else 
    Item.all 
    end 
end 

def self.custom_scope(scope) 
    recent if scope == 'recent' 
    active if scope == 'active' 
    inactive if scope == 'inactive' 
    scoped if scope.blank? 
end 

,然后在指数

@items = Item.custom_scope params[:scope] 
0

是这样的:

if ['recent', 'active', 'inactive'].include?(params[:scope]) 
    @items = Item.send(params[:scope]) 
else 
    @items = Item.all 
end