Cyber
Cyber

Reputation: 5000

How to Include additional field in Rails 3 Application JSON Response

I have a Rails application which displays nested form in json format.

In the JSON Response i am also displaying an id field which represent another table.

How to display name corresponding to that id what i am getting so that i can display both name and id in my json format.

My controller show method

def show
    @maintemplate = Maintemplate.find(params[:id])
    respond_with (@maintemplate) do |format|
      format.json { render :json => @maintemplate }
    end
  end

Thanks in advance....

Upvotes: 3

Views: 2404

Answers (2)

Carson Cole
Carson Cole

Reputation: 4451

Add to as_json method with the additional method-attributes you desire to the class in which you are calling.

class MainTemplate
  ...

  def name
    User.find(self.user_id).name
  end

  def as_json(options = {})
    options[:methods] = :name
    super(options)
  end

end

Upvotes: 1

Chris Salzberg
Chris Salzberg

Reputation: 27374

Try this:

render :json => @maintemplate.to_json(:include => { :user => { :only => :name } } )

This will replace the user_id key with a user key and a value with only the name attribute of user, like this:

{
  "user_id": "12"
  "user": { "name": "..." }
  ...
}

You can then access the username in the json response with ["user"]["name"]. You can also access the user id with ["user_id"].

For more see the documentation on as_json.

Update:

Using the info provided in the comments, I think this is what you actually want:

render :json => @maintemplate.to_json(:include => { :routine => { :include => :user, :user => { :only => :name } } } )

Upvotes: 4

Related Questions