ruby on rails 3 - Find_by_sql and calculated field -
i using find sql, , want calculate in database , add together model.
i wil seek simplify code
class user < activerecord::base attr_accessor :comments_count end
and somewhere else:
@users = user.find_by_sql("select * (select count(*) comments user_id=u.id) comments_count users u") @user.map{|u| puts u.comments_count}
any help?
activerecord will, unfortunately, not match selected columns attributes on model. however, easy set together. first you'd need overload find_by_sql
-
def self.find_by_sql(sql) values = connection.select_all(sql) objects = [] values.each |row| objects << self.new(row) end objects end
then initialize function model can mass assign schema-based attributes, , handle assigning custom attributes. not clean or simple solution hoping for, should accomplish task. , write initialize function generic, in can mass assign schema-based attributes, , match leftover keys passed in attributes may nowadays on self
.
ruby-on-rails-3 activerecord
No comments:
Post a Comment