这是协会,
出版物
:有_many exchange_rates
、书籍
和作者
书籍
belongs_to author
, exchange_rate
作者
belongs_to exchange_rate
我正在尝试编写一个查询来查找带有一个额外computed_column
的books
。
这是我到目前为止尝试过的查询,
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
最佳答案
在 Book
上添加 computed_column
作为 attr_accessor
class Book
attr_accessor :computed_column
end
那么您查询中的每个 Book
实例都会有可用的 book.computed_column
关于mysql - ActiveRecord 深层嵌套查询和计算列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28233869/