codedog
codedog

Reputation: 2508

Can I define a query in Rails model?

Here's what I have:

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

I have bits of code elsewhere using the is_future_show? method. What I would like to do is have a method in the module mixin to return "future shows" using a query that has the same criteria as the is_future_show? method. How would I go about achieving this? I'm very much a newbie to Rails but tainted by knowledge of other languages and frameworks.

Cheers, Dany.

Upvotes: 3

Views: 2396

Answers (1)

Alex Peattie
Alex Peattie

Reputation: 27637

You can put the query into a scope:

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

Call it like this:

my_event.shows.future

Edit: Ah I see. To return all events with a show in the future:

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

agains this can be scoped:

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

On a side note, I'm not sure about the setup of your models, especially the use of the mixin. Here's what I do:

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

also it would be cleaner if the show_date column for the Show model was just called date (so you could just write show.date rather that show.show_date).

Upvotes: 2

Related Questions