【问题标题】:Rails scopes with multiple arguments具有多个参数的 Rails 范围
【发布时间】:2014-08-18 14:27:42
【问题描述】:

在我的 offer.rb 模型中,我正在对拥有这些优惠的客户进行一些过滤。 但我希望能够在我的范围内传递另一个参数来搜索,例如,客户的年龄左右。

这就是我现在的报价模型中的内容:

scope :with_client_id, lambda { |client_id| where(:client_id => client_id) }

在视图中:

<%= f.select(:with_client_id, options_for_select(current_partner.clients.collect{|c| [c.name, c.id]}), { include_blank: true}) %>

在这个范围内,我怎样才能传递客户的年龄?

谢谢!

【问题讨论】:

    标签: ruby-on-rails lambda filtering named-scopes


    【解决方案1】:

    两个选项

    使用“splat”

    scope :with_client_id_and_age, lambda { |params| where(:client_id => params[0], :age => params[1]) }
    

    然后你必须调用它:

    Offer.with_client_id_and_age( client_id, age )
    

    使用参数哈希

    scope :with_client_id_and_age, lambda { |params| where(:client_id => params[:client_id], :age => params[:age]) }
    

    然后你必须调用它:

    Offer.with_client_id_and_age( { client_id: client_id, age: age } )
    

    【讨论】:

      【解决方案2】:

      我保持范围不变,只是修改了视图中的选择:

      <%= f.select(:with_client_id, options_for_select(current_partner.clients.collect{|c| [c.name_and_age, c.id]}), { include_blank: true}) %>
      

      使用客户端控制器中的 name_and_age 方法:

      def name_and_age
        [name, age].compact.join " "
      end
      

      我也可以在 select2 框中输入一些年龄来进行过滤。

      【讨论】:

        猜你喜欢
        • 2020-09-22
        • 2014-10-11
        • 2015-02-14
        • 2014-08-26
        • 2020-05-10
        • 1970-01-01
        • 2022-10-15
        • 2015-01-20
        • 1970-01-01
        相关资源
        最近更新 更多