Rails 2.3.8 named_scope链接

时间:2011-06-07 22:53:47

标签: ruby-on-rails named-scope

我有以下嵌套if语句毛球,我想知道是否有更有效的方法来编写这段代码(更少的代码行不需要这么多的条件)

每个方法都是模型中的named_scope ..

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

我的想法是我可以使用'call'类型的方法来显示框和

@current_user.received_messages.call(:box).call(:show).all

也许..?

UGH,应该花更多的时间玩耍......就像我想的那样,我只是使用了错误的方法解决方案

@current_user.send(box).send(show)

3 个答案:

答案 0 :(得分:3)

您可以使用rails 2.3.8中的scoped()方法来链接范围:

main_method = case (params[:s]||"inbox")
when "inbox"
  :received_messages
when "sent"
  :sent_messages
end
# create a scope. Don't execute the scope yet. 
scope = @current_user.send(main_method).scoped({}) if main_method

# now chain the scope if needed
scope = begin
  if ["unread", "read", "starred"].include?(params[:s])
    scope.send(params[:s])
  elsif((params[:s] || "all") == "all")
    scope
  end
end if main_method == :received_messages

@messages = scope.nil? ? [] : scope.all

<强>参考:

Scoped method source in Rails 2.3.x

Rails casts on Anonymous scopes in 2.3.x

答案 1 :(得分:0)

这就是我想到的,我不打算将自己的答案标记为正确,除非大家都同意这是最好的 - 任何其他想法?

if params[:b].present? && ["received_messages", "sent_messages"].include?(params[:b])
  box = params[:b]

  if params[:s].present? && ["all", "unread", "starred"].include?(params[:s])
    show = params[:s]
  else
    show = "all"
  end

  @messages = @current_user.send(box).send(show)
else
  @messages = []
end

答案 2 :(得分:0)

您的答案非常接近但无法转换box值。

box  = params[:b] || 'inbox'
show = params[:s] || 'all'

box_scope = case box
  when 'inbox' then 'received_messages'
  when 'sent'  then 'sent_messages'
end
show_scope = show # no convertion needed at this point, maybe in the future

# If box_scope is nil, don't query
@messages = box_scope.nil? ? [] : @current_user.send(box_scope).send(show_scope)

这假设您取消了在所有选项的原始代码中使用的.all,这些选项在您的答案中消失了。