Get associated attribute using to_json method

Hi all,

I hv the following model:

class User < ActiveRecord::Base
has_and_belongs_to_many :roles

def user_role
self.roles
end
end

class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end

When I run the following code:
user = User.find(:first)
user.to_json

there’s no user_role attribute displayed. but when I run
user.user_role, it can give the expected result.
So, how can I get the associated attribute when using to_json ?

Appreciate for your help.

Take a look at these:

http://blog.codefront.net/2007/07/11/better-json-output-from-rails-with-the-jsonifier-plugin/
http://dev.rubyonrails.org/ticket/9677

Basically, you need an :include

Arshak

Infinit wrote:

Hi all,

I hv the following model:

class User < ActiveRecord::Base
has_and_belongs_to_many :roles

def user_role
self.roles
end
end

class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end

When I run the following code:
user = User.find(:first)
user.to_json

there’s no user_role attribute displayed. but when I run
user.user_role, it can give the expected result.
So, how can I get the associated attribute when using to_json ?

Appreciate for your help.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs