2

这是我的三个模型/表格

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

我想从这三个表中返回所有字段,而不仅仅是从一个表中返回(比如 Swing_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?

谢谢你的帮助

4

2 回答 2

2

请试试这个,我有一个疑问,要么我们必须把模型的名称和命名空间放在join

Swimming::Classschedule.joins(:classtime).joins(:timeblock).select("swimming_classtimes.*,swimming_timeblocks.*,swimming_classschedules.*")
于 2013-06-08T08:54:13.773 回答
1

您正在寻找的是:加入嵌套关联。在你的情况下,你会这样做:

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

希望下面将提供一个额外的示例并说明上面发生的事情: 在此处输入图像描述

于 2014-12-28T18:44:55.690 回答