0

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?

Timm
  • 1,005
  • 8
  • 20

1 Answers1

2

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(...)
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
  • Thanks alot, `default_scope` was exactly what I was looking for. Setting `client_id` when creating and initializing is not a disadvantage, it saves me some code as I first wanted to do this by adding `after_save` filters. – Timm Sep 07 '14 at 10:52