2

Here are the associations,

Publication : has_many exchange_rates, books and authors

Book belongs_to author, exchange_rate

Author belongs_to exchange_rate

I am trying to write a query to find books with one extra computed_column.

This is the query I have tried so far,

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")

My aim is to generate a column which computed from associated tables attributes.

That means,

book.exchange_rate.exchange_ratio + book.author.exchange_rate.exchange_ration AS computed_column
Sourabh Upadhyay
  • 1,034
  • 11
  • 31

1 Answers1

0

Add computed_column as an attr_accessor on Book

class Book
  attr_accessor :computed_column
end

Then each instance of Book in your query will have book.computed_column available

For reference: Access SQL computed columns through ActiveRecord

Community
  • 1
  • 1
Daniel Ma
  • 646
  • 5
  • 10