2

我试图弄清楚如何从多个表中提取数据并理解它。

我有events,occurrencesvenues表。

以下是迄今为止的模型/协会:

模型/事件.rb:

class Event < ActiveRecord::Base
 has_many :occurences, :dependent => :destroy
 belongs_to :price
 belongs_to :venue
 validates_presence_of :venue
end

模型/地点.rb:

class Venue < ActiveRecord::Base
 has_many :events, :dependent => :destroy
end

模型/occurrence.rb:

class Occurence < ActiveRecord::Base
 belongs_to  :event
 scope :today, lambda { where("occurence.datetime_start <= ? AND datetime_end >= ?", Time.now.end_of_day, Time.now) }
 scope :this_week, lambda { where("occurence.datetime_start <= ? AND datetime_end <= ?", Time.now.end_of_day, Time.now.at_end_of_week) }
 scope :next_week, lambda { where("occurence.datetime_start > ? AND datetime_end < ?", Time.now.at_end_of_week, Time.now.at_end_of_week + 1.weeks) }
 scope :this_month, lambda { where("occurence.datetime_start <= ? AND datetime_end >= ?", Time.now.end_of_day, Time.now.at_end_of_month) }
 scope :next_month, lambda { where("occurence.datetime_start >= ? AND datetime_end <= ?", Time.now.at_beginning_of_month + 1.months, Time.now.at_end_of_month + 1.months) }
end

我想在我的 view/events/index.html.erb 中显示的是今天发生的所有事件的表格,我喜欢这样做:

<% @events.today.each do |event|  %>

并显示与.today范围匹配的所有事件。

我尝试将范围移动到event模型无济于事。我应该将范围移动到事件模型吗?到目前为止,我的搜索已经引导我到“使用范围在 ActiveRecord 中的多个 DateTime 范围内返回结果”和“ Rails 3.0 中的多个范围”,但我真的无法从中做出任何事情。

谁能指出我正确的方向?我应该在我的事件模型中创建一个新函数吗?

4

2 回答 2

3
class Event < ActiveRecord::Base
  has_many :occurences, :dependent => :destroy
  belongs_to :price
  belongs_to :venue
  validates_presence_of :venue

  scope :today, lambda {
    joins(:occurences).where("datetime_start <= ? AND datetime_end >= ?", Time.now.end_of_day, Time.now)
  }
end
于 2012-10-23T17:22:05.857 回答
1

如果你希望你的语法像这样工作:

@events.today

然后范围必须在Event模型中。

如果你没问题:

@event.occurences.today

那么你现在可以了,即:

@events = Event.all
@events.each do |ev|
   ev.occurences.today.each do |oc|
   end
end
于 2012-10-23T17:27:55.667 回答