使用has_many连接2个表中的数据

时间:2014-03-12 13:57:16

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

我正在尝试加入来自2个模型的数据,但它似乎比它应该更难。模型:

class Content < ActiveRecord::Base
  has_many :times

  scope :current, ->(time) do
    includes(:times).joins(:times).where("start_time < ?", time)
  end

end

class Time < ActiveRecord::Base
  belongs_to :contents
end

现在,当我调用@content.current(Time.new)生成正确的SQL并返回AssociationRelation时,我可以找到Content个对象。这很好,但问题是我也想访问与@content关联的时间模型中的数据并符合条件(where("start_time < ?", time)) 我的问题是,如果我访问@content.current(Time.new).first.times,我会获得所有Time个对象,还是仅获取从加入生成的对象?如果不是,从两个模型获取数据的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我强烈建议您更改时间模型的名称:

  • 时间已经是class in Ruby
  • 函数Fixnum #times返回一个枚举器,可能会有时干扰

也许您可以将模型重命名为Occurence


  

&#34;如果我访问Content.current(Time.new).first.times我会得到所有   时间的对象或仅从连接中生成的对象?&#34;

是的,您只能访问与此Content对象相关的Time对象。


我建议您稍微改进一下代码:

class Content < ActiveRecord::Base
  has_many :occurences

  scope :before, ->(time = Time.current) do
    includes(:occurences).where("occurences.start_time < ?", time)
  end

end

class Occurence < ActiveRecord::Base
  belongs_to :content
end

# usage:
Content.before.first.times # default value for .before() scope is Time.current
Content.before(Time.current - 1.years)

@content = Content.before.first
@occurences_of_this_content = @content.occurences
相关问题