Rails 3.2 Scope with optional parameter

I have the following area for finding a product belonging to a particular customer.

scope :client, lambda {|client| where("client_id = ?", client) } 

and can be called

 Product.client(parameter) 

Is there a way to declare my area to return all products if no customer ID is provided? Is this a situation where the scope should not be used?

+4
source share
2 answers

You should use something other than scope, since you really want to switch between the two cases (with or without the specified client ID) 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 scope output, so you can cling to it, etc.

Note that this also picks up code and does not require a specific area. And make sure you don't actually have has_many :clients for Product anyway ...

+1
source

It can work fine with areas

 scope :client, lambda {|client = nil| where("client_id = ?", client) unless client.nil? } 
+6
source

All Articles