[英]Accessing attributes from other model
I have 3 models : User, Location, Picture. 我有3个型号:用户,位置,图片。 A Location has several pictures, and a User can provide several pictures. 一个位置有几张图片,用户可以提供多张图片。 I use rabl to render the result of my query in json. 我使用rabl在json中呈现我的查询结果。 My problem is that I don't know how to display the user name from the user id in this relation ? 我的问题是我不知道如何在这种关系中显示用户ID的用户名?
I designed my models like that : 我设计了我的模型:
Picture : 图片:
class Picture < ActiveRecord::Base
...
belongs_to :location
belongs_to :user
...
end
User : 用户:
class User < ActiveRecord::Base
...
has_many :pictures
accepts_nested_attributes_for :pictures
attr_accessible :name, :email
...
end
Location : 位置 :
class Location < ActiveRecord::Base
...
has_many :pictures, :dependent => :destroy
accepts_nested_attributes_for :pictures
attr_accessible :name, :address
...
end
My rabl file : 我的拉布文件:
object false
collection @locations
attributes :id, :name, :address
child :pictures do
attributes :id, :location_id, :url, :user_id, :created_at
end
I tried to add :user_name in the child :pictures block, but obviously it fails... How can I access it ? 我试图在子:picture块中添加:user_name,但显然它失败了......我怎样才能访问它?
EDIT : When I add 编辑:当我添加
node(:user_name) { |picture| picture.user.name }
as mentioned by Jesse, I get this error in the logs : 正如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'
Thanks ! 谢谢 !
You can use the same node
method in the child block as if you were on the main part. 您可以在子块中使用相同的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.