Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

ruby - How could we replace the ? from the rails sql query

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: "[email protected]" }])
# SELECT * FROM users WHERE name = 'Joe' AND email = '[email protected]';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...