I have the following scope for finding a product that belongs to a specific client.
scope :client, lambda {|client| where("client_id = ?", client) }
and can be called by
Product.client(parameter)
Is there any way I can declare my scope to return all products if a client id is not given? Is this a situation where a scope shouldn't be used?
It can work OK with scopes
scope :client, lambda {|client = nil| where("client_id = ?", client) unless client.nil? }
You should use something other than a scope, since you really want to switch between the two cases (with/without a client id specified) and respond differently. How about this:
class Product < ActiveRecord::Base
def self.by_client(client)
if client
where(client_id: client)
else
all
end
end
end
This code will always return something like the output of scope, so you can chain with it etc.
Note that this also tidies up the code and doesn't require a particular scope. And make sure you don't actually mean to have has_many :clients for the Product anyway...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With