views:

23

answers:

1

When I print an ActiveRecord of a Department, I get:

Department:0x210ec4c { :id => 3, :name => "Computer Science", ... :school_id => 3 }

How can I make it give me the School instead of the School_ID? In other words, call to_s on the school found by the school_id. Just like how when I have a Department d, I can say

d.school

To clarify, I'm asking specifically about PRINTING the ActiveRecord, and about the Department CLASS rather than a particular instance. I was wondering if there's a way to PATCH ActiveRecord so that when I PRINT the Department class in the console, I get each Department's school.to_s instead of school.id

A: 

If your assosciation like following

class School < ActiveRecord::Base
  has_many :departments, :dependent => :destroy
end

class Department < ActiveRecord::Base
  belongs_to :schools, :dependent => :destroy
end

Then

@department =Department.find(1) #For example here
@department.school #gives you the school object
# (i assume you are saving schoolname in 'name' column of schools table) 
@department.school.name  #This gives you school name
Salil
OK, sorry I wasn't clear enough in my question. I was asking specifically about PRINTING the ActiveRecord, and about the Department CLASS rather than a particular instance. I was wondering if there's a way to patch ActiveRecord so that when I print the Department class in the console, I get each Department's school.to_s instead of school.id
marienbad