简体   繁体   中英

create active record query for virtual attribute in Rails 5 or 6

If I have a virtual attribute such as full_name , composed of first_name + " " + last_name , and I want to find users with User.where(full_name: "John Whoosiwhatsit") , how can I do this?

This was apparently not possible back in Rails 3 (or whatever was current 8 years ago) , but it seems like it may have been made possible since then.

And yes, I know that in the example given there are problems when you have "Anne Marie Van Der Moss", but the point of the question is about how to do this type of thing, not whether the particular example is a good idea or easy to implement well.

User.select("users.*", "CONCAT(users.first_name, ' ', users.last_name) AS full_name")
    .where(full_name: "John Whoosiwhatsit")

This will work on MySQL, Postgres and SQLite (and probally more). ActiveRecord will map any aliased columns in the resulting rows from the query as attributes in the model.

Some dbs (like Oracle) don't let you use aliases in the WHERE clause so you would have to repeat the concatenation:

# Use an Enterprise DB they said. It will be fun they said.
User.select("users.*", "CONCAT(users.first_name, ' ', users.last_name) AS full_name")
    .where("CONCAT(users.first_name, ' ', users.last_name) = 'John Whoosiwhatsit'")

This has probally worked in almost every version since Rails AFAIK has always allowed you to revert to raw SQL if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM