有没有办法在单表继承类中重写as_json?

时间:2015-06-23 08:39:17

标签: ruby-on-rails

给定模型用户:

class User < ActiveRecord::Base
  self.inheritance_column = :meta_type
  scope :doctors, -> { where(meta_type: 'Doctor') }
  scope :patients, -> { where(meta_type: 'Patient') }

  def as_json(options={})
    super( (options || {}).merge({ :methods => [:profile_url]}))
  end

  def profile_url
    self.image(:small)
  end
end

Doctor和Patient类均继承自User class:

class Doctor < User
  has_many :patients, :through #other irrelevant code  
end

class Patient < User
  has_one :doctor  
  has_many :conditions 
end

我希望能够做的是在我的Patient类中覆盖患者特定方法的as_json。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

就像你和用户一样做?

class Patient < User
  has_one :doctor  
  has_many :conditions

  def as_json(options={})
    super( (options || {}).merge({ :methods => [:your_patient_methods]}))
  end

end
相关问题