问题
I need help with SELECT FROM nested SELECT.
How can I rewrite following query in an ActiveRecord way and get an Relation object?
SELECT candidates.*
FROM (SELECT (candidates.first_name || ' ' || candidates.last_name) AS full_name, candidates.* FROM candidates) candidates
WHERE full_name = 'Anton Kolganov'
回答1:
Why do you concatenate instead of selecting based on first and last name? The subselect will be much less performant than direct query. You could get the full name using the select scope (it will be accessible in the same way as other attributes):
Candidate.select("candidates.*, (first_name || ' ' || last_name) AS full_name").
where(first_name: 'Antonov', last_name: 'Kolganov')
Update: If you really needed to rewrite the above query with a subselect in the FROM clause to ActiveRecord, you can do the following:
Candidate.from("(SELECT (candidates.first_name || ' ' || candidates.last_name) AS full_name, candidates.* FROM candidates) candidates").
where(full_name: 'Anton Kolganov')
I.e., in general, you can put any valid SQL into the ActiveRecord scope methods, including select, from, etc.
回答2:
There are multiple ways. You will have to try and see if the results fit your needs by converting the query to sql or checking the results.
Candidates.where(other_query).where(SELECT (candidates.first_name || ' ' || candidates.last_name) AS full_name, candidates.* FROM candidates) candidates
WHERE full_name = 'Anton Kolganov')
You could also use a join or a select insterad of a where.
If you don't want to resort to plain sql you can use gems like Arel or Squeel
来源:https://stackoverflow.com/questions/37377455/activerecord-nested-select