开发者

Why are my associations not rendered to JSON?

I'm trying to control the JSON rendering of a user object in Rails开发者_运维问答 3.0.2. Here's the relevant model code:

class User < ActiveRecord::Base

  belongs_to :employer
  has_and_belongs_to_many :roles

  def as_json(options={}) 
    super(options.merge(:include => [:employer, :roles])) 
  end
end

Here's the JSON representation I get:

{"user":{"employer":{},"roles":[{},{},{}],"email":"user.user@example.com"}}

This user does have three roles, so somehow the :include statement is looking up the association, but the role and employer objects are not getting converted to JSON.

If I had an as_json to either of those models, returning garbage, it still doesn't show up.

Am I doing something wrong, or is this a bug? (It wasn't rendering anything for the associations until I upgraded from Rails 3.0.0, which I learned to do from this question.)


You can try: to_json(:include => [:employer, :roles]) in place of as_json

http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html


My workaround

I'm still not sure why it didn't work, but my workaround is to build the representation I wanted manually.

  def serializable_hash(options={}) 
    hash_info = super(options) 
    hash_info[:employer] = {:name => employer.name}
    hash_info[:roles] = roles
    hash_info
  end

I'm using serializable_hash because that is a more general-purpose method from which Rails can generate JSON or XML or whatever. But the method works the same if you change the name to as_json.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜