Get the JSON representation of a model and an association

71 views Asked by At

A QuestionTag belongs_to a Tag.

I want to get the JSON representation of a QuestionTag, and some information from the Tag it belongs to. What is the correct Rails-Activerecord query to get me this structure from a controller action?

{
  question_id: 1,
  name: "PHP",
  description: "A programming language for monkeys."
}

Here are the tables:

QuestionTag
  question_id
  tag_id

Tag
  name
  description
1

There are 1 answers

2
Arslan Ali On BEST ANSWER

In you controller, when you send back the response in JSON format, you can do something like following:

respond_to do |format|
  format.json do
    render :json => @tag.to_json(:include => { :question_tag => { :only => :question_id } })
  end
end

Now, it will send response in the following format. It will send only question_id form QuestionTag table.

{
  name: "name",
  description: "description",
  question_id: 0
}