views:

414

answers:

4

Hi all, lets say i have the following relationship:

class Event < ActiveRecord::Base
  has_many :tickets
end

class Ticket < ActiveRecord::Base
 belongs_to :event
end

And I have a route like this:

  map.resources :events, :has_many => :tickets
  map.resources :tickets

And i have a before filter like this on tickets_controller:

 before_filter :get_event

def get_event
  @event = Event.find(params[:event_id])
end

And I have an index action on tickets_controller like this:

if @event == nil
  @tickets = Ticket.all
else
  @tickets = @event.tickets.all   
end

how come if I go to /tickets (where no event instance is passed) it says I still need an event id?

I am trying to keep DRY otherwise i would separate the index action into to actions and exclude one in the before filter.

appreciate the help!

A: 

The code in your before_filter is being called

@event = Event.find(params[:event_id])

and it requires an event_id.

Because of the version of find you are using, that is the version that is looking for a specific id, you are getting a RecordNotFound exception.

You may want to use

Event.first(params[:event_id])

and check for nil on that.

Laz
that makes sense! appreciate the help Laz!
drpepper
A: 

The other way to handle it is to exclude the filter from the index action:

before_filter :get_event, :except => [:index]

Then place

@events = Event.all

into the index action. Since you will most likely only listing a limited number of events, perhaps:

@events.Event.all(:limit => 10)
askegg
A: 

You need first to check for the presence of the event_id.

  @event = Event.find(params[:event_id]) if params[:event_id]
mark
A: 

the way I would do it is

begin
  @event = Event.find(params[:event_id])
rescue ActiveRecord::RecordNotFound
  # do nothing -- can be written to do redirects but not necessary here
end

Also, you can write if @event == nil as if !@event (note not unless @event since the else makes the unless confusing.

Omar Qureshi