Question: I have a teacher model which has\_many students. When I render a student (as json) I want to strip out the teacher\_id property and replace it with the name of the teacher in my representation.

What is the best way to achieve this?

Cheers,

Chris

Answer: 
Define a method called `teacher_name`.

```
class Student < ActiveRecord::Base
  def teacher_name
    self.teacher.name
  end
end

```

Include the `teacher_name` method while invoking `to_json`:

```
teacher.to_json(:include => {:students => {:methods=> :teacher_name, 
                                           :except => :teacher_id
                                          }
                            }
                )

```
You can always redefine the to\_json method on the model to do whatever you want:

```
class Student < ActiveRecord::Base
  def to_json
    self.attributes.merge(
      'teacher_id' => self.teacher.name
    ).to_json
  end
end

```

**Update:** Based on feedback from [kandadaboggu](https://stackoverflow.com/users/163203/kandadaboggu) , using a different approach:

```
class Student < ActiveRecord::Base
  def teacher_name
    self.teacher and self.teacher.name
  end

  def to_json(options = { })
    super(
      {
        :methods => :teacher_name,
        :except => :teacher_id)
      }.merge(options)
    )
  end
end

```

Note that when using a brute-force merge like this the result is sometimes less than satisfactory, but will serve for the default case. If you specify :methods or :except options of your own, the defaults will be ignored.