2011-06-08 48 views
-1

我有两个模型Location和LocationType。Rails,CamalCase Model Name检索相关记录?

class LocationType < ActiveRecord::Base 
    has_many :locations 
end 

class Location < ActiveRecord::Base 
    belongs_to :location_type 
end 

在我的选址模型我有外键:location_type_id

在我看来,我试着拨打:

@location.location_type.name 

,但我得到一个错误:

未定义方法`name'为零:NilClass

如何获得显示location_type相关记录的视图?

+0

你的数据库看起来像什么?你可以给我们@location的价值吗? – 2011-06-08 03:24:36

+0

@location有:name =“TEST1”,:map_url =“http:// ....”,并且location_type_id = 1 – Mike 2011-06-08 03:53:29

回答

0

检查Location对象上的location_type_id。如果没有该对象的LocationType对象,则@location.location_type将返回零。

+0

location_type = 1并且在该ID中存在location_types中的记录 – Mike 2011-06-08 03:52:03

+0

使用'rails console'尝试检查并查看@ location.location_type的计算结果。 – robbrit 2011-06-08 03:59:18

+0

@ location.location_type返回正确的location_type记录,但@ location.location_type.name => nil – Mike 2011-06-08 04:07:16