2011-02-16 98 views
0

我在轨中有一些嵌套的对象。用户 - > has_many:任务 - > has_one:位置。如何获取子对象的值

昨天,我以为我在将位置值链接到任务时遇到了问题,但现在我意识到我无法在显示中输出值。

我可以通过调试得到输出

 
<%= for task in @user.tasks %> 
     <%= debug task.locations %> 
<% end %> 

输出

 
--- !ruby/object:Location 
attributes: 
    id: "1" 
    address: "testing address" 
    city: "chicago" 
attributes_cache: {} 

changed_attributes: {} 

etc. etc. etc. 

所以我想,如果我用

 
<%= task.locations.address %> 

的Rails会给我的地址字段。但我得到一个

undefined method 'address' for nil:NilClass

对我有什么错误的任何建议吗?

----------更新,包括模型---------------- 我的任务模型&位置是

 
class Task < ActiveRecord::Base 
    attr_accessible :user_id, :date, :description, :location_id 

    belongs_to :user 
    has_one :location 
end 

class Location < ActiveRecord::Base 
    attr_accessible :address, :city, :state, :zip 

    has_many :tasks 
end 

回答

2

如果任务has_one位置,则在位置结束时您需要执行task.location.address而不是s,因为has_one返回实际对象而不是集合。在调用地址方法之前,您还需要确保您的位置存在,否则在无位置的情况下会出错。您可能对尝试方法感兴趣,例如task.location.try(:address)

+0

我看到你在看什么,并更新了问题以显示我的模型。不幸的是,这并不能解决问题。有没有一种方法可以显示嵌套模型是否可用,以及导轨期望的是什么:位置或位置? – pedalpete 2011-02-16 23:47:41