简体   繁体   中英

Rails scopes with multiple arguments

In my offer.rb model I am doing some filtering after clients who have these offers. But I want to be able to pass another param in my scope to search by, for example, the age of a client or so.

This is what I have now in my offer model:

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

In the view:

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

How can I pass a client's age per say in this scope?

Thanks!

Two Options

Using a "splat"

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

And then you'd have to call it with:

Offer.with_client_id_and_age( client_id, age )

Using a params hash

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

And then you'd have to call it with:

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

I left the scope unchanged and just modified the select in the view:

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

With the name_and_age method in the clients controller:

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

I can type some age too in the select2 box to make the filterring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM