【问题标题】:Elegant way to pass only non-null parameters in rails redirect_to在 rails redirect_to 中仅传递非空参数的优雅方式
【发布时间】:2025-12-30 01:50:12
【问题描述】:

我们如何在 rails redirect_to 方法中只传递非空参数?

我知道我们可以通过以下方式将参数传递给redirect_to:

redirect_to :action => "action1", :foo => bar

当变量 'bar' 可能为 nil 或为空时,是否有任何优雅/更好的方法来传递它?

现在,我在做redirect_to 之前检查bar 是否为空白。但我觉得这可以用更优雅的方式来完成。

if bar.blank?
    redirect_to :action => "action1"
else
    redirect_to :action => "action1", :foo => bar
end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    使用可选参数创建路由

    get '/action1/(:foo)' => 'controller#action1'
    

    然后像这样使用它

    redirect_to :action => "action1"
    

    redirect_to :action => "action1", :foo => bar
    

    更多信息http://guides.rubyonrails.org/routing.html#bound-parameters

    【讨论】:

    • 如何更优雅?
    • 不是更优雅的方式,但即使参数为 nil 并避免 if else 条件,它也会起作用
    • 我不知道路由中的可选参数。这看起来是使用 nil 参数的好方法。
    【解决方案2】:

    这里没有真正好的选择,但也许其中一个会帮助激发一个想法:


    args = { :action => "action1" }
    args[:foo] = bar unless bar.blank?
    redirect_to args
    

    redirect_to { :action => "action1" }.tap do |args|
      args[:foo] = bar unless bar.blank?
    end
    

    redirect_to { :action => "action1" }.merge!(bar.blank? ? {} : { :foo => bar })
    

    【讨论】:

      【解决方案3】:

      试试:

      redirect_to :action => "action1", bar.blank? ? {} : :foo => bar
      

      【讨论】:

      • 如果bar 为空,这将在传递给redirect_to 的结构中嵌套一个奇怪的哈希元素,类似于{:action=>"action1", {}=>" "}(其中值是bar 的值,因为奇怪运算符优先级)。
      • 请编辑更多信息。不建议使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。