Find_by_sql and computed field
I am using find my sql and I want to calculate something in the database and add to my model.
I will try to simplify the code
class User < ActiveRecord::Base
attr_accessor :comments_count
end
And somewhere else:
@users = User.find_by_sql("select * (select count(*) from comments where user_id=u.id) as comments_count from Users u")
@user.map{|u| puts u.comments_count}
Any help?
source to share
OK I understood. It has nothing to do with attr_accessor. I had to remove it.
@users = User.find_by_sql("select * (select count(*) from comments where user_id=u.id) as comments_count from Users u")
@user.map do |u|
puts u.comments_count if @user.has_attribute?(:comments_count)
end
source to share
ActiveRecord, unfortunately, doesn't just map any selected columns to attributes on the model. However, something like this will probably be pretty easy to put together. First you need to overload find_by_sql
something like this:
def self.find_by_sql(sql)
values = connection.select_all(sql)
objects = []
values.each do |row|
objects << self.new(row)
end
objects
end
Then the initialization function for your model can massively assign schema-based attributes and then handle the assignment of your custom attributes. It's not an easy or straightforward solution as you probably hoped, but it should get the job done. And you could probably write the initialize function to be pretty generic, as it can massively assign all the schema-based attributes and then map the remaining keys that were passed in with whatever attributes it might have on self
.
source to share