I am trying to the get SQL from AREL, but it does not work in case I use average(:stars) :
This works:
Review.where("reviewed_user_id = ?", self.reviewed_user_id).to_sql
#=> "SELECT `reviews`.* FROM `reviews` WHERE (reviewed_user_id = 3)"
This causes NoMethodError:
Review.where("reviewed_user_id = ?", self.reviewed_user_id).average(:stars).to_sql
#=> undefined method `to_sql' for 3:Fixnum
So that means that to_sql is getting called on the result of the AREL instead of on the AREL object – but why?
How to get the generated SQL ?
The reason this is happening is because the average method is on
ActiveRecord::Relation, not Arel, which forces the computation.By checking out the internals of
ActiveRecord::Calculations, you can derive how to get at the SQL that it uses.Careful if you’re working at the console.
ActiveRecord::Relationcaches things so if you type the above into the console line by line, it will actually not work, because pretty-printing forces the relation. Separating the above by semicolons and no new lines, however, will work.Alternatively, you can use Arel directly, like so: