我有以下嵌套的if语句hairball,我想知道是否有更有效的方式来编写此代码(不需要这么多条件的代码行)Rails 2.3.8 named_scope链接
每种方法都named_scopes模型中..
box = (params[:b] ? params[:b] : "inbox")
show = (params[:s] ? params[:s] : "all")
if box == "inbox"
if show == "all"
@messages = @current_user.received_messages.all
elsif show == "unread"
@messages = @current_user.received_messages.unread.all
elsif show == "read"
@messages = @current_user.received_messages.read.all
elsif show == "starred"
@messages = @current_user.received_messages.starred.all
else
@messages = []
end
elsif box = "sent"
@messages = @current_user.sent_messages.all
else
@messages = []
end
我的想法是,我可以用一个“呼叫”型方法的框,显示像
@current_user.received_messages.call(:box).call(:show).all
也许..?
哎,应该花一点更多的时间玩了..其正当我以为,我只是使用了错误的方法SOLUTION
@current_user.send(box).send(show)
我不知道范围的方法,这基本上是在轨道3之前arel魔术的步骤?所以我可以创建查询,然后在附加所有条件后运行它? – Rabbott 2011-06-08 15:46:23
我已经添加了一些对该方法的引用。观看指定的Railscast以获取更多信息。 – 2011-06-08 16:27:37
真棒谢谢你!这是除了轨道2.3.9?在2.3.8中不可用? – Rabbott 2011-06-08 20:21:46