好吧,在视图助手中,hack 可能是这样的:
def link_to_delete_event( event, participation = nil )
final_path = participation.nil? ? event_path( event ) : event_path( :id => event, :participation_id => participation )
link_to 'Delete event', final_path, :confirm => 'Are you sure?', :method => :delete
end
在您看来,您将使用link_to_delete_event( event )单独删除事件,并使用 link_to_delete_event( event,participation )删除参与。您的控制器可能是这样的:
def destroy
@event = Event.find(params[:id])
unless params[:participation_id].blank?
@event.destroy
else
@event.participations.find( params[:participation_id] ).destroy
end
redirect_to somewhere_path
end
编辑
为了减少黑客攻击,您应该为事件下的参与创建一个嵌套资源:
map.resources :events do |events|
events.resources :participations
end
然后你必须创建一个ParticipationsController,它看起来像这样:
class ParticipationsController < ApplicationController
before_filter :load_event
def destroy
@participation = @event.participations.find( params[:id] )
@participation.destroy
redirect_to( event_path( @event ) )
end
protected
def load_event
@event = Event.find( params[:event_id] )
end
end
并且 link_to 助手会变成这样:
def link_to_delete_event( event, participation = nil )
if participation
link_to 'Remove participation', event_participation_path( event, participation ), :method => :delete
else
link_to 'Delete event', event_path( event ), :confirm => 'Are you sure?', :method => :delete
end
end