我有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
我的拉布文件:
object false
collection @locations
attributes :id, :name, :address
child :pictures do
attributes :id, :location_id, :url, :user_id, :created_at
end
我试图在child: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'
谢谢!
答案 0 :(得分: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