sqlruby-on-railsactiverecordwhere-clausedefault-scope

Force where in ActiveRecord model in Rails


Is there any way to force a where statement to be included in every SELECT-statement I do with Active Record? I'm using Rails 4.

For example: If I call:

Product.where(name: 'Fishing rod')

Then I want Rails to generate a SQL query like the following:

SELECT * FROM products WHERE products.client_id = 1 AND (name = 'Fishing rod')

where products.client_id = 1 is the forced where statement. All other conditions I define via where or other ORM-methods (like find or whatever) should be included in the statement aswell.

Is there a possibility to define such forced condition?


Solution

  • You can do this with default_scope

    In your model

    default_scope { where(client_id: 1) }
    

    According to the docs

    The default_scope is also applied while creating/building a record. It is not applied while updating a record.

    because of this I would recommend that you use a more explicit method and define a named scope like this

    scope :client_one, -> { where(client_id: 1) }
    

    which you would use like this then

    Product.client_one.where(...)