Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 815
Bogdan Popa Avatar asked Apr 20 '26 15:04

Bogdan Popa


1 Answers

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 } )
like image 143
Joshua Pinter Avatar answered Apr 22 '26 03:04

Joshua Pinter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!