gpt4 book ai didi

ruby-on-rails - ActiveRecord 关联和范围哦,我的

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:36 25 4
gpt4 key购买 nike

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

我有 eventsoccurrencesvenues 表。

以下是到目前为止的模型/协会:

模型/事件.rb:

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

模型/ field .rb:

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

模型/occurence.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 模型,但没有成功。我应该将范围移动到事件模型吗?到目前为止,我的搜索引导我到“Using scope to return results within multiple DateTime ranges in ActiveRecord”和“Multiple scope in rails 3.0 “但我真的无法从中得到任何东西。

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

最佳答案

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

关于ruby-on-rails - ActiveRecord 关联和范围哦,我的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13035757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com