简体   繁体   English

使用attr_accessor返回导航字段值

[英]Use attr_accessor to return navigation field value

I have a belongs_to relation in my Patient model, then I need to create an attr_accessor to read the state_id from the city specified in the Patient object. 我的患者模型中有一个归属关系,然后需要创建一个attr_accessor来从患者对象中指定的城市读取state_id。

How can I do this? 我怎样才能做到这一点?

If I just use attr_accessor :state_id, I'd have to set it in the class initialization and the value would be static. 如果仅使用attr_accessor:state_id,则必须在类初始化中进行设置,并且该值将是静态的。 I need it to be read only and updated automatically according to the current value of City navigation property. 我需要它是只读的,并根据“城市”导航属性的当前值自动更新。

You don't need an attr_accessor you just need a method. 您不需要attr_accessor ,而只需要一个方法。

class Patient

  def state_id
    city.state_id
  end

end

If the city association is optional you may want to handle the possibility of city being nil... 如果城市协会是可选的,则您可能要处理城市为零的可能性。

class Patient

  def state_id
    city.try(:state_id)
  end

end

If you want your API for your Patient object to look something like @patient.state_id , then either SteveTurczyn's answer or delegation could work for you in order to read the state_id from the city specified in the Patient object: 如果您希望您的Patient对象的API看起来像@patient.state_id Patient.state_id ,那么SteveTurczyn的答案委托都可以为您工作,以便从Patient对象中指定的城市读取state_id:

class Patient
  # you can remove `allow_nil` if the patient will *always* have a city
  delegate :state_id, to: :city, allow_nil: true
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM