开发者

Activerecord method for "as" - Derived Alias

开发者 https://www.devze.com 2023-02-15 23:09 出处:网络
I am trying to build a SQL query using ActiveRecord methods.The query has a few joins which require derived tables, like this:

I am trying to build a SQL query using ActiveRecord methods. The query has a few joins which require derived tables, like this:

(SELECT voteable_id, COUNT(vote) FROM votes WHERE vote = 0 GROUP BY voteable_id) AS example

My problem is that I cannot seem to find a method that would allow me to create an alias for my derived table (here: AS example). My question thus is, is it even possible to build such a query using activerecord methods?

EDIT: just to make it more clear. I have the following methods to build the select statement.

t = Vote # Vote being the table name
t = t.where("vote = 0")
t = t.group("voteable_id")
t.select("voteable开发者_运维百科_id, COUNT(vote)")

but how would I go about adding the "AS" alias?


You could always use the result of #to_sql:

t = Vote # Vote being the table name
t = t.where("vote = 0")
t = t.group("voteable_id")
sql = t.select("voteable_id, COUNT(vote)").to_sql
t.connection.find_by_sql("(#{sql}) AS example")

The real question is why you need to use an alias. Answer that and we'll be better placed to help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消