how to get values of child object
I've got some nested objects in rails. User -> has_many :tasks -> has_one :location.
Yesterday, I thought I was having trouble linking the location values to the task, but now I realize that I'm not able to get the values to output in show either.
I can get the output via debug
<%= for task in @user.tasks %> <%= debug task.locations %> <% end %>
outputs
--- !ruby/object:Location attributes: id: "1" address: "testing address" city: "chicago" attributes_cache: {} changed_attributes: {} etc. etc. etc.
So I thought if I used
<%= task.locations.address %>
Rails would give me the address field. but I get an
undefined method 'address' for nil:NilClass
any suggestions on what I've got wrong?
---------- update, including models --------------开发者_如何学JAVA-- My models for tasks & locations are
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
If task has_one
location, you'll need to do task.location.address
without the s
at the end of location, as has_one
returns the actual object and not a collection. You'll also need to be sure your location exists before calling it's address method or you'll get an error in case of a nil location. You could be interested in the try method, such as task.location.try(:address)
.
精彩评论