开发者

Adding the sum of a has_many relationship to a model's attributes

开发者 https://www.devze.com 2023-03-09 11:38 出处:网络
I have the following (simplified model) and wish to access the \'spent\' value in the to_json method of the object, ideally as an attribute of the object.

I have the following (simplified model) and wish to access the 'spent' value in the to_json method of the object, ideally as an attribute of the object.

class Task < ActiveRecord::Base
  has_many    :hours

  def spent
    self.hours.sum(:spent)
  end
end

Is there a way to do this without defining a method and hacking the to_json method? I've been hunting for a way to use scope or by hacking the after_initialize method, but none of these methods provide a 'spent' v开发者_运维技巧alue when using inspect or to_json on the model.

I need to solve this on models higher up the tree that use a has_many, through relationship too.


You can use the :methods parameter to to_json call.

object.to_json(:methods => :spent)

http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html


The best solution I could find to this was overriding the 'as_json' method to include the attributes that I needed, or to perform the logic required, (in this case the sum of the has_many relationship).

class Task < ActiveRecord::Base

...

  def as_json(options = { })
    options = {} if options.nil?

    self[:job_id] = self.phase.job_id
    self[:spent] = self.hours.sum(:spent)

    super(options)
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消