Ruby on rails 嵌套资源中未定义的方法有一个
我使用rails 4.02。(强参数) 3种型号:Ruby on rails 嵌套资源中未定义的方法有一个,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我使用rails 4.02。(强参数) 3种型号: class Region < ActiveRecord::Base has_many :cities end class City < ActiveRecord::Base has_one :location end class Location < ActiveRecord::Base belongs_to :city end 我收到错误消息未定义的方法“纬度” 这是完整的跟踪: activerecord
class Region < ActiveRecord::Base
has_many :cities
end
class City < ActiveRecord::Base
has_one :location
end
class Location < ActiveRecord::Base
belongs_to :city
end
我收到错误消息未定义的方法“纬度”
这是完整的跟踪:
activerecord (4.0.3) lib/active_record/relation/delegation.rb:13:in each' activerecord
(4.0.3) lib/active_record/relation/delegation.rb:13:in each' actionpack (4.0.3)
lib/action_view/template.rb:143:in block in render' activesupport (4.0.3)
lib/active_support/notifications.rb:161:in instrument' actionpack (4.0.3)
lib/action_view/template.rb:141:in render' actionpack (4.0.3)
lib/action_view/renderer/template_renderer.rb:49:in block (2 levels) in render_template'
我做错了什么?谢谢如果您的
位置
模型确实具有纬度
属性,则导致此错误的最可能原因是您的数据库中有一些城市
记录的位置
值为零。您可以通过查看完整的异常消息来检查是否存在这种情况,是否类似于:
NoMethodError: undefined method `latitude' for nil:NilClass
在这种情况下,您有两种选择,取决于您是否考虑<代码>纬度>代码>是您的代码>锡蒂< /C> >模型的必需属性。如果需要,则通过向您的
城市
模型添加验证规则来强制执行该规则:
validates :location, presence: true
以及对数据库模式中的外键列的NOTNULL约束
或者,如果应用程序中允许缺少latitude
值,您可以在视图中处理缺少的值:
= city.location.try(:latitude)
是否
位置/位置
表格/模型
有任何纬度
列/属性您的代码中似乎没有任何错误。请更新完整的错误跟踪。同时在城市中添加所属的地区。还有一件事,您应该在位置表中包含city_id,以使其正常工作。是的,位置表具有属性latitude。我用logactiverecord(4.0.3)lib/active\u record/relation/delegation更新了这个问题。rb:13:ineach'activerecord(4.0.3)lib/active\u record/relation/delegation.rb:13:in
each'actionpack(4.0.3)lib/action\u view/template.rb:143:inrender'activesupport(4.0.3)lib/active\u支持/通知。rb:161:in
instrument'actionpack(4.0.3)lib/action\u视图/模板。rb:141:inrender'actionpack(4.0.3)lib/action\u视图/渲染器/模板渲染器。rb:49:in
块(2层)in render\u模板'actionpack(4.0.3)lib/action\u view/renderer/abstract\u renderer.rb:38:init不可读,请在您的帖子中发布您的wright steve…有些记录的值为零。谢谢,现在可以用了!
= city.location.try(:latitude)