Reputation: 10208
I am using find my sql, and I want to calculate something in the database and add to my model.
I wil 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?
Upvotes: 3
Views: 375
Reputation: 10208
Ok, i got it. 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
Upvotes: 1
Reputation: 2746
ActiveRecord will, unfortunately, not just match any selected columns to attributes on the model. However, something like that would probably be fairly easy to put together. First you'd need to overload find_by_sql
to 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 initialize function for your model can mass assign the schema-based attributes, and then handle assigning your custom attributes. Its not as clean or simple a solution as you were probably hoping for, but it should accomplish the task. And you could probably write the initialize function so that it is fairly generic, in that it can mass assign all the schema-based attributes, and then match leftover keys that were passed in with any attributes that may be present on self
.
Upvotes: 1