Rails:通过join获取多个模型的所有字段

时间:2013-06-09 00:32:20

标签: ruby-on-rails ruby ruby-on-rails-3

以下是三种模式:

class Swimming::Classschedule < ActiveRecord::Base
  belongs_to :swimming_classtimes ,:class_name=>'Swimming::Classtime',:foreign_key => "classtime_id"  
  attr_accessible :id,:coach_id, :level_id, :note, :classtime_id
end


class Swimming::Classtime < ActiveRecord::Base
  has_many :swimming_classschedules,:class_name=>'Swimming::Classschedule'
  belongs_to :swimming_timeblocks ,:class_name=>'Swimming::Timeblock',:foreign_key => "timeblock_id"    
  attr_accessible :date, :end, :start,:timeblock_id,:id
end


class Swimming::Timeblock < ActiveRecord::Base
  has_many :swimming_classtimes,:class_name=>'Swimming::Classtime'
  has_many :swimming_classschedules,:class_name=>'Swimming::Classschedule',:through => :swimming_classtimes
  attr_accessible :name,:id
end 

我尝试加入这三个模型

schedules = Swimming::Classschedule.joins(:swimming_classtimes=>:swimming_timeblocks).select("swimming_classtimes.*,swimming_timeblocks.*,swimming_classschedules.*").where("swimming_classtimes.date >= '2013-06-01' and swimming_classtimes.date <= '2013-06-08' ")

这是返回的结果

=> [#<Swimming::Classschedule id: 7, coach_id: nil, level_id: nil, note: nil, created_at: "2013-06-08 23:24:31", updated_at: "2013-06-08 23:24:31", lesson_id: 1, classtime_id: 24, lane_id: nil, program_id: nil, classtype_id: nil>]

为什么它只返回swimming_classschedules中的字段。我希望从三个模型返回所有​​字段

"swimming_classtimes.*,swimming_timeblocks.*,swimming_classschedules.*"

缺少什么?

1 个答案:

答案 0 :(得分:1)

Swimming :: Classschedule具有仅为其db列定义的属性。您可以使用

访问其他字段

对象[:COLUMN_NAME]

例如:

schedules.first[:timeblock_id]