How can I chain a scope after a class method, or ignore the class method's
default sorting?
I need to find a workaround so I can filter my @events by the .is_near
method then sort them by the .sort_today scope, in that order.
Individually they both work, and I can tack .is_near to the end of the
scope with no problem, but then my results are resorted by the default
sort parameters in .is_near, and I need to them to be sorted by
.sort_today.
Is there a way to ignore how .is_near returns/resorts my results? Or
someway to chain them together like
@events.is_near(session[:city]).sort_today? Currently I get this error
when chaining them like that: undefined method `sort_today' for
#Array:0x007f8ca3c673c0
Here's my models:
class Venue < ActiveRecord::Base
attr_accessible :name, :address, :latitude, :longitude
has_many :events, :dependent => :destroy
geocoded_by :address
def self.is_near(city)
self.near(city, 20, :units => :km).map(&:events).flatten
end
end
class Event < ActiveRecord::Base
attr_accessible :title, :details, :start_time, :end_time, :date, :cost,
:venue_id
belongs_to :venue
scope :is_today, where(:date => Date.today)
scope :sort_today, is_today.order(:start_time)
class << self
def is_near(*args, &block)
Venue.is_near(*args, &block)
end
end
end
So Venue is geocoded by the RubyGeocoder gem and it has all the events.
The .is_near method has to be in Venue because the latitude and longitude
properties are there. The .is_near method at the bottom of Event is
essentially a redirect. (I tried to get delegate to work, but this was the
only way I could do it)
Here's my controllers:
class EventsController < ApplicationController
def index
@events = Event.sort_today.is_near(session[:city]) #returns results
but sorted wrong
#@events = Event.is_near(session[:city]).sort_today #returns undefined
method `sort_today' error
end
end
class ApplicationController < ActionController::Base
before_filter :set_city
def set_city
unless session[:city].present?
session[:city] = request.location.city
end
end
end
The set_city method just gets what city the user enters through a input
field.
No comments:
Post a Comment