Question

I have 3 models : User, Location, Picture. A Location has several pictures, and a User can provide several pictures. I use rabl to render the result of my query in json. My problem is that I don't know how to display the user name from the user id in this relation ?

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 ?

EDIT : When I add

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

as mentioned by Jesse, I get this error in the logs :

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 !

Was it helpful?

Solution

You can use the same node method in the child block as if you were on the main part.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top