rails加入模型混乱(加入多个表)

时间:2013-06-08 05:49:05

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

这是我的三个模特/桌子

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'
  attr_accessible :name,:id
end

我想做一个内部联接

 select * from swimming_classschedules as c inner join swimming_classtimes as t on c.classtime_id = t.id inner join swimming_timeblocks as b on c.timeblock_id = b.id where c.date >= "2013-06-01" and c.date <= "2013-07-01" and c.timeblock_id = 5

我希望不仅从一个表(比如swim_classschedules)返回这三个表中的所有字段。我已阅读此页http://guides.rubyonrails.org/association_basics.html但仍不清楚如何使用rails模型进行内部连接

更新

尝试了第一个答案

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

收到此错误消息

ActiveRecord::ConfigurationError: Association named 'swimming_timeblocks' was not found; perhaps you misspelled it?

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

请试试这个,我有一个疑问,要么我们必须在join

中添加带名称空间的模型名称
Swimming::Classschedule.joins(:classtime).joins(:timeblock).select("swimming_classtimes.*,swimming_timeblocks.*,swimming_classschedules.*")

答案 1 :(得分:1)

您正在寻找的内容称为:joining nested associations。以下是您在案件中的表现方式:

Swimming::Classschedule.joins(:classtime => :timeblock).
select("swimming_classtimes.*,swimming_timeblocks.*,swimming_classschedules.*")

希望以下内容将提供一个额外的示例,并说明上面发生了什么: enter image description here