ruby on rails - Accessing attributes from other model -


i have 3 models : user, location, picture. location has several pictures, , user can provide several pictures. use rabl render result of query in json. problem don't know how display user name user id in relation ?

i designed models :

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   attributes :id, :location_id, :url, :user_id, :created_at end 

i tried add :user_name in child :pictures block, fails... how can access ?

edit : when add

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

as mentioned jesse, error in 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' 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 same node method in child block if on main part.

collection @locations  attributes :id, :name, :address  child :pictures   attributes :id, :location_id, :url, :user_id, :created_at   node(:user_name) {|picture| picture.user.name} end 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -