开发者

Pass method chains to to_json

开发者 https://www.devze.com 2022-12-16 08:25 出处:网络
I know you can pass methods the values of which you want to be available to json objects like so: # user.rb

I know you can pass methods the values of which you want to be available to json objects like so:

# user.rb
def name
  first_name + last_name
end

# some controller
render :json => @user.to_json(:methods => :name)

But if I want to massage the value returned 开发者_如何学编程from the method a bit (with a text helper say) is there a way to do that? I guess another way to ask this is does #to_json support arbitrary attributes? If not, why not? Has anyone else ran into this before?


You can use "render :json" to specify arbitrary attributes in the JSON output. Here is an example:

render :json => { :arbitraryAttribute => arbitrary_method_to_call(), :user => @user.to_json }

The above code would generate JSON like the following:

{
    "arbitraryAttribute":"returnValueOfMethodCall",
    "user":{ the result of @user.to_json }
}
0

精彩评论

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