2013-08-07 3 views
0

3 가지 모델이 있습니다 : 사용자, 위치, 그림. 위치는 그림이 여러 개 있으며 사용자가 그림을 여러 개 제공 할 수 있습니다. rabl을 사용하여 json에서 내 쿼리의 결과를 렌더링합니다. 내 문제는이 관계에있는 사용자 ID에서 사용자 이름을 표시하는 방법을 모르겠다는 것입니다.다른 모델의 속성에 액세스하기

사진 :

class Picture < ActiveRecord::Base 
... 
    belongs_to :location 
    belongs_to :user 
... 
end 

사용자 :

class User < ActiveRecord::Base 
... 
    has_many :pictures 

    accepts_nested_attributes_for :pictures 

    attr_accessible :name, :email 
... 
end 

위치 :

class Location < ActiveRecord::Base 
... 
    has_many :pictures, :dependent => :destroy 

    accepts_nested_attributes_for :pictures 

    attr_accessible :name, :address 
...  
end 

내 rabl 파일 :

01,235

나는 그런 내 모델 설계
object false 
collection @locations 

attributes :id, :name, :address 

child :pictures do 
    attributes :id, :location_id, :url, :user_id, :created_at 
end 

아이 : 그림 블록에 user_name을 추가하려고했으나 분명히 실패했습니다 ... 어떻게 액세스 할 수 있습니까?

편집 : 제시에 의해 언급 한 바와 같이 나는

node(:user_name) { |picture| picture.user.name } 

를 추가, 나는 로그에이 오류를 얻을 :

2013-08-08T00:20:18.911561+00:00 app[web.1]: 
2013-08-08T00:20:18.911561+00:00 app[web.1]: ActionView::Template::Error (undefined method `name' for nil:NilClass): 
2013-08-08T00:20:18.911561+00:00 app[web.1]:  1: object false 
2013-08-08T00:20:18.911561+00:00 app[web.1]:  2: collection @locations 
2013-08-08T00:20:18.911561+00:00 app[web.1]:  3: 
2013-08-08T00:20:18.911561+00:00 app[web.1]:  4: attributes :id, :name, :address, :city, :state, :zipcode, :country_name, :latitude, :longitude, :distance 
2013-08-08T00:20:18.911561+00:00 app[web.1]:  5: 
2013-08-08T00:20:18.911561+00:00 app[web.1]: app/views/api/v1/locations/index.json.rabl:2:in `_app_views_api_v__locations_index_json_rabl___4323955523361468965_70365132977020' 

감사합니다!

답변

2

메인 블록에있는 것처럼 하위 블록에서 동일한 node 메서드를 사용할 수 있습니다.

collection @locations 

attributes :id, :name, :address 

child :pictures do 
    attributes :id, :location_id, :url, :user_id, :created_at 
    node(:user_name) {|picture| picture.user.name} 
end 
+0

감사합니다. 그러나이 줄을 추가하면 로그에 이상한 오류가 표시됩니다. 제 질문을 참조하십시오. 감사! – jbihan

+0

죄송합니다. 내 실수였습니다. 내 그림에 사용자가 연결되어 있지 않아 이름이 null 개체를 가리키고있었습니다 ... 답변 해 주셔서 감사합니다. 완벽하게 작동합니다! – jbihan

관련 문제