我有以下嵌套的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