Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3.2 Scope with Optional Parameter

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?

like image 902
ctilley79 Avatar asked Feb 20 '23 02:02

ctilley79


2 Answers

It can work OK with scopes

scope :client, lambda {|client =  nil| where("client_id = ?", client) unless client.nil? }
like image 196
Wawa Loo Avatar answered Mar 05 '23 05:03

Wawa Loo


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...

like image 35
Peter Avatar answered Mar 05 '23 07:03

Peter