views:

19

answers:

1

I have an events model which has two named scopes:

class Event < ActiveRecord::Base
  scope :future, lambda { where('events.date >= ?', Time.zone.now) }
  scope :past, lambda { where('events.date <= ?', Time.zone.now) }
end

I call these scopes from my controller by creating two new controller actions (named "future" and "past"):

My controller:

class EventsController < InheritedResources::Base
  actions :index, :show, :future, :past

  has_scope :future
  has_scope :past

  def future
    index! { @events = Event.future }
  end

  def past
    index! { @events = Event.past }
  end
end

I also have views and routes for these additional actions.

This works fine. My application does what I want and I can link to the new actions in my sidebar as follows:

%li
  = link_to 'Events Home', events_path
%li
  = link_to 'Future Events', future_events_path
%li
  = link_to 'Past Events' past_events_path

Now my problem with this setup is that, whilst it works just fine, I don't like the fact that I have to create new actions, views and routes for these extra scopes. I don't think I'm doing this the right way. Essentially I'm trying to filter the results on the index page but I'm having to create new actions, routes and views to do this. It seems a little cumbersome and I'm wondering if there is another way.

It would be nice if I could do away with the "future" and "past" controller actions and just call the scopes from the view like this:

%li
  = link_to 'Events Home', events_path
%li
  = link_to 'Future Events', events_path.future
%li
  = link_to 'Past Events' events_path.past

Obviously that doesn't work. I've seen an example that uses a custom select_tag helper but I can quite modify it to work without a select tag or JS...

Is it better to stick with the current method

+1  A: 

You could have only the index action and pass the scope as a parameter, so you would do:

Event.send(params[:scope] : 'all')

The scope could be passed like:

link_to "Future events", events_path(:scope => "future")
jordinl
thanks a lot, that works perfectly - it really helps!
stephenmurdoch