1
scope :accessible_by, -> (current_user) { where("loc_primary_email= ? OR loc_backup_email= ? ",current_user.email, current_user.email) }

How could I replace ? with :email so, that I don't need to pass current_user.email twice in query

kshitiz
  • 11
  • 1
  • 1
    Take a look at the docs for [`where`](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where) – there's even an example with `email = ?` and `email = :email` – Stefan Jan 06 '21 at 13:58
  • Does this answer your question? [Is there a DRY way to pass bind variables to an AR Relation?](https://stackoverflow.com/questions/14526389/is-there-a-dry-way-to-pass-bind-variables-to-an-ar-relation) – Cristik Jan 07 '21 at 05:35

1 Answers1

2

You can replace it just like that, for the "?":

scope :accessible_by, -> (current_user) { where("loc_primary_email = :email OR loc_backup_email = :email ", email: current_user.email) }

But then the argument for where must contain a hash, where the email key must be present.

You can check the docs for this, using an array of as argument (of course, you can omit the brackets);

Alternatively, you can use named placeholders in the template, and pass a hash as the second element of the array. The names in the template are replaced with the corresponding values from the hash.

User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
# SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59