oyaji's Blog

rails model associations

 

Rails中ActiveRecord finders不允许我们在include预加载关联对象时使用select。
 
例如这样的情况:
 
class Student < ActiveRecord::Base
   has_many :calls
   has_one :call
end

class Call < ActiveRecord::Base
   belongs_to :student
end
希望在显示student时,显示它的最近更新的call的日期。
 
改善前:
 
@students = Student.all(:include => [:call])
改善后:
 
#include eql left outer join
@students = Student.all(:select => "students.id, students.login, students.called_times,
calls.updated_at as last_called_at", :joins => "left outer join calls on students.id = calls.student_id")
 
前几天在rails performance turning中发现:
跨数据库的应用中在model层指定associations,以及用include实现的提前装载,
和through实现的多表关联,都不起作用。
但奇怪的是在console中却能正常的取到值。。。求解
 
 




Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee