Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用attr\u访问器返回导航字段值_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails 使用attr\u访问器返回导航字段值

Ruby on rails 使用attr\u访问器返回导航字段值,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,在我的患者模型中有一个归属关系,然后我需要创建一个attr\u访问器,从患者对象中指定的城市读取state\u id 我该怎么做 如果我只使用attr\u accessor:state\u id,我必须在类初始化中设置它,并且该值将是静态的。我需要它是只读的,并根据城市导航属性的当前值自动更新 你不需要一个attr\u访问器你只需要一个方法 class Patient def state_id city.state_id end end 如果城市协会是可选的,您可能希望处理

在我的患者模型中有一个归属关系,然后我需要创建一个attr\u访问器,从患者对象中指定的城市读取state\u id

我该怎么做


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

你不需要一个
attr\u访问器
你只需要一个方法

class Patient

  def state_id
    city.state_id
  end

end
如果城市协会是可选的,您可能希望处理城市为零的可能性

class Patient

  def state_id
    city.try(:state_id)
  end

end

如果您希望
患者
对象的API看起来像
@Patient.state\u id
,则可以使用或从患者对象中指定的城市读取state\u 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