Thursday, February 9, 2012

Adventures in moving from Rails 2.3.14 to 3.0: Has_many through


There have been many blogs about moving from Rails 2.3x to 3.0. Kir Maximov has a good one. And there is the Simone Carletti's blog which gives some pre-migration advice.

I am going to focus on the things that I encountered that I could not find mentioned elsewhere, and may be peculiar to my application.

Each day that I work on the migration, I am going to post what I encountered. Mostly, this will help me if I ever have to do another migration. And it keeps me off the streets.


Issue with has_many through
I have the following has_many through relationship
class Parent
  has_many :relatives
  has_many :students, :through => :relatives
end

class Relative
  belongs_to :parent
  belongs_to :student
end

In the parent class, I had the following named_scope:

named_scope :in_school_year, lambda{|s,y|
    {:include => {:students => {:homerooms => :classroom}}, 
    :conditions => ['classrooms.year = ? and classrooms.school_id = ?', y, s.id]}
  } 


In 2.3.x, this worked fine. But in 3.0, this created a query where the relatives table was not being joined to the students table, so was returning all students.

I changed the scope in the rails 3 version of my app to the following, and it worked fine.

scope :in_school_year, lambda{|s,y|
    {:include => {:relatives => {:student => {:homerooms => :classroom}}}, 
    :conditions => ['classrooms.year = ? and classrooms.school_id = ?', y, s.id]}
  } 

Perhaps it never should have worked in rails 2.3, but it did.

No comments:

Post a Comment