开发者

How can I add a property to child association before render?

I have a teacher model which has_many students. When I r开发者_StackOverflow社区ender a student (as json) I want to strip out the teacher_id property and replace it with the name of the teacher in my representation.

What is the best way to achieve this?

Cheers,

Chris


Define a method called teacher_name.

class Student < ActiveRecord::Base
  def teacher_name
    self.teacher.name
  end
end

Include the teacher_name method while invoking to_json:

teacher.to_json(:include => {:students => {:methods=> :teacher_name, 
                                           :except => :teacher_id
                                          }
                            }
                )


You can always redefine the to_json method on the model to do whatever you want:

class Student < ActiveRecord::Base
  def to_json
    self.attributes.merge(
      'teacher_id' => self.teacher.name
    ).to_json
  end
end

Update: Based on feedback from kandadaboggu , using a different approach:

class Student < ActiveRecord::Base
  def teacher_name
    self.teacher and self.teacher.name
  end

  def to_json(options = { })
    super(
      {
        :methods => :teacher_name,
        :except => :teacher_id)
      }.merge(options)
    )
  end
end

Note that when using a brute-force merge like this the result is sometimes less than satisfactory, but will serve for the default case. If you specify :methods or :except options of your own, the defaults will be ignored.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜