Right now I have a controller for “events” that belong to a specific
user. I only want the creator to be able to edit or delete the event.
I’ve got the proper foreign keys set up.
I’ve finally arrived at the point where I can take baby steps with
code, but looks like my first steps are in flagrant violation of the
DRY principle.
Here’s what I have so far in the “EventsController” and I know it’s
ugly (but it works).
def update
@event = Event.find(params[:id])
if @event.user_id == session[:user] &&
@event.update_attributes(params[:event])
flash[:notice] = ‘Event was successfully updated.’
redirect_to :action => ‘show’, :id => @event
else
flash[:notice] = ‘You do not have permission to edit.’
redirect_to :action => ‘list’
end
end
def destroy
@event = Event.find(params[:id])
if @event.user_id == session[:user]
@event.destroy
redirect_to :action => ‘list’
flash[:notice] = ‘Event was deleted.’
else
flash[:notice] = ‘You do not own this event.’
redirect_to :action => ‘list’
end
end
What I would like to do is extract the “if @event.user_id ==
session[:user]” kind of verification from controllers since I can
imagine calling this a lot as I add more models with a variety of
permissions?
Is there a better strategy to approach this?
Sam