Karol Selak
Karol Selak

Reputation: 4774

How to make SQL query in ActiveRecord using alias for the table?

I want to make such a query for my Services ActiveRecord in Rails:

SELECT *
FROM "services" AS s
WHERE /* part using 's' alias */

Normally I'd write just Service.where(/* where part */), but I need to set my alias.

I tried to run ActiveRecord::Base.connection.execute(query), but result of that is not recognized as Service.

How can I handle it?

Upvotes: 2

Views: 3113

Answers (2)

Tom Copeland
Tom Copeland

Reputation: 1271

To use a table alias combine the select method with from:

Service.select("s.*").from("services s")

Which generates this SQL:

SELECT s.* FROM services s

And it returns an ActiveRecord::Relation which you can refine as needed.

Upvotes: 6

Karol Selak
Karol Selak

Reputation: 4774

Fortunately I found solution during writing this question. Service.find_by_sql(query) works well in my case.

Upvotes: 0

Related Questions