【发布时间】:2014-02-23 17:38:28
【问题描述】:
我将过滤功能放入应用程序(Rails 4.1beta) - 我通过在 Item 模型上创建范围、通过请求参数传递范围并在索引操作中执行 case 语句来做到这一点。一切正常,但我正试图在其中一个控制器的索引操作中消除代码异味;
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 类的方法的人敞开大门。那里的恶劣条件有点违背了我想要实现的目标。
我是否缺少一些可以帮助我的 Rails 魔法?
【问题讨论】:
标签: ruby-on-rails controller scope