ActiveRecord深层嵌套查询和计算列

时间:2015-01-30 10:30:21

标签: mysql ruby-on-rails activerecord nested-queries

以下是关联,

Publication:has_many exchange_ratesbooksauthors

Book belongs_to authorexchange_rate

Author belongs_to exchange_rate

我正在尝试编写一个查询,以便在books之后找到computed_column

这是我到目前为止尝试的查询

publication.books.joins(:exchange_rate, :author).select("books.*, (exchange_rates.exchange_ratio + (SELECT exchange_rates.exchange_ratio FROM exchange_rates WHERE exchange_rate_id = authors.exchange_rate_id)) AS computed_column")

我的目标是生成一个根据关联表属性计算的列。

这意味着,

book.exchange_rate.exchange_ratio + book.author.exchange_rate.exchange_ration AS computed_column

1 个答案:

答案 0 :(得分:0)

computed_column

上添加attr_accessor作为Book
class Book
  attr_accessor :computed_column
end

然后,查询中的Book每个实例都会book.computed_column可用

供参考:Access SQL computed columns through ActiveRecord