ユーザー、場所、画像の 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ファイル:
object false
collection @locations
attributes :id, :name, :address
child :pictures do
attributes :id, :location_id, :url, :user_id, :created_at
end
子の :pictures ブロックに :user_name を追加しようとしましたが、明らかに失敗しました...どうすればアクセスできますか?
編集:追加すると
node(:user_name) { |picture| picture.user.name }
Jesse が述べたように、ログに次のエラーが表示されます。
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'
ありがとう !