使用attr_accessor返回导航字段值

时间:2016-04-13 21:21:08

标签: ruby-on-rails ruby-on-rails-4

我的Patient模型中有一个belongs_to关系,然后我需要创建一个attr_accessor来读取Patient对象中指定的city_id。

我该怎么做?

如果我只使用attr_accessor:state_id,我必须在类初始化中设置它,值将是静态的。我需要它只读,并根据城市导航属性的当前值自动更新。

1 个答案:

答案 0 :(得分:0)

您不需要attr_accessor,只需要一种方法。

class Patient

  def state_id
    city.state_id
  end

end

如果城市协会是可选的,你可能想要处理城市没有的可能性......

class Patient

  def state_id
    city.try(:state_id)
  end

end
相关问题