Overwrite default json rendering for active record object
1. Suppose you have made a JSON request and got
Published in
1 min readMay 19, 2010
[sourcecode language=”javascript”]
[
{ “student_id”: 1, “subject_id” : 1, “score” : 7 }
{ “student_id”: 1, “subject_id” : 2, “score” : 8 }
]
[/sourcecode]
2. student_id and subject_id?
But what you need is actually student name and subject name NOT id.
3. So…
Go to your active record model and add
[sourcecode language=”ruby”]
…
def to_json(options)
self.attributes.merge(
‘student_name’ => self.student.name,
‘subject_name’ => self.subject.name
).to_json(:except => [:student_id, :subject_id])
end
…
[/sourcecode]