开发者

To_Json overriding in Ruby

I have an object in Ruby called Post. I would like to convert post into an json but also I want to include the name of the user who posted the post. The thing is user_name is not present in Post object but the user id is.

开发者_Python百科

So what I effectively want is something like this

{name:"My Post", body:"My post data", user_name:"jhonny"}

When I do a to_json on Post object I get following

{name:"My Post", body:"My post data"}

But I also want to append user_name:"jhonny" part also to it. I know I can make it a hash and then do a to_json on the hash, but I do not want to make the hash for all the post values manually as there are many attributes to post. I'd rather user a hash merge function to add the additional attribute to hash and then call json on it.

Is there a way to make a quick hash object for a ruby class? Any ideas will be welcome.

Something like

my_post.hash.merge{:user_name => "jhonny"}.to_json

Cheers.


Answering your question should be something like this

my_post.attributes.merge{:user_name => "jhonny"}.to_json

Anyway if that didn't work then just try one of the following solutions:

Add this to your Post model:

def to_json
  ActiveRecord::JSON.decode(super).merge({:user_name => user.user_name}).to_json
end

Another solution will be adding user_name method to the Post model:

def user_name
  user.user_name
end

Then use to_json as follows:

my_post.to_json(:methods => :username)


If your Post model is ActiveRecord model, it accepts :except, :include and :only parameters for serialization methods, #to_json included. See the details and examples here in the AR documentation.

Basically you'll need something like

my_post.to_json(:include => { :user => { :only => :user_name } })
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜