# Get associated attribute using to\_json method

**URL:** <https://www.ruby-forum.com/t/get-associated-attribute-using-to-json-method/132631>\
**Category:** Rails\
**Created:** [March 22, 2008, 7:40am UTC](https://www.ruby-forum.com/t/get-associated-attribute-using-to-json-method/132631 "2008-03-22T07:40:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![infinit](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/76d3ee/32.png) [@infinit](https://www.ruby-forum.com/u/infinit)\
**Post date:** [March 22, 2008, 7:40am UTC](https://www.ruby-forum.com/t/get-associated-attribute-using-to-json-method/132631/1 "2008-03-22T07:40:05Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![infinit](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/76d3ee/32.png) [@infinit](https://www.ruby-forum.com/u/infinit)\
**Post date:** [March 24, 2008, 3:50am UTC](https://www.ruby-forum.com/t/get-associated-attribute-using-to-json-method/132631/2 "2008-03-24T03:50:23Z")

</div>

Take a look at these:

[http://blog.codefront.net/2007/07/11/better-json-output-from-rails-with-the-jsonifier-plugin/](http://blog.codefront.net/2007/07/11/better-json-output-from-rails-with-the-jsonifier-plugin/)  
[http://dev.rubyonrails.org/ticket/9677](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.
