我可以在Rails模型中定义查询吗?

时间:2011-10-22 05:31:47

标签: ruby-on-rails ruby activerecord ruby-on-rails-3.1

这就是我所拥有的:

module EventDependencyProperties
  def start_date
    shows.order('show_date ASC').first.show_date
  end

  def end_date
    shows.order('show_date DESC').first.show_date
  end

  def is_future_show?
    end_date >= Date.today 
  end
end

class Event < ActiveRecord::Base
  include EventDependencyProperties
  has_many :shows
  has_and_belongs_to_many :users
end

class Show < ActiveRecord::Base
  belongs_to :event
end

我在其他地方使用is_future_show?方法获得了一些代码。我想要做的是在模块mixin中使用一个方法,使用与is_future_show?方法具有相同条件的查询返回“future shows”。我将如何实现这一目标?我是Rails的新手,但受到其他语言和框架知识的污染。

干杯, 达尼。

1 个答案:

答案 0 :(得分:2)

您可以将查询放入a scope

class Show < ActiveRecord::Base
  scope :future, lambda { where("show_date > ?", Date.today) }
end

这样称呼:

my_event.shows.future

编辑:我明白了。要在将来通过节目返回所有活动:

Event.joins(:shows).where("shows.show_date > ?", Date.today)

这可以是作用范围:

class Event
  scope :future, lambda { joins(:shows).where("shows.show_date > ?", Date.today) }
end

另一方面,我不确定您的模型的设置,尤其是mixin的使用。这是我的所作所为:

class Show < ActiveRecord::Base
  belongs_to :event

  # use default_scope so shows are ordered by date by default
  default_scope order("show_date ASC")
end

class Event < ActiveRecord::Base
  has_many :shows
  has_and_belongs_to_many :users

  scope :future, lambda { joins(:shows).where("shows.show_date > ?", Date.today) }

  def start_date
    shows.first.show_date
  end

  def end_date
    shows.last.show_date
  end

  def ends_in_future?
    end_date > Date.today
  end
end

如果Show模型的show_date列刚刚调用date,那么它也会更清晰(所以你可以写show.date而不是show.show_date)。