0

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 ---------------- 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 
4

1 に答える 1

2

タスクの場所の場合、コレクションではなく実際のオブジェクトを返すため、場所の最後にを付けずhas_oneに行う必要があります。また、addressメソッドを呼び出す前に、場所が存在することを確認する必要があります。そうしないと、場所がnilの場合にエラーが発生します。などのtryメソッドに興味があるかもしれません。task.location.addressshas_onetask.location.try(:address)

于 2011-02-16T21:55:16.063 に答える