在Ruby on Rails中仅删除连接表记录

我有以下简单的模型:

class Event  :participations end class Participation < ActiveRecord::Base belongs_to :event belongs_to :user end class User  :participations end 

在我看来,我想要做的是,根据当前用户角色,删除事件及其参与记录,或者仅删除参与记录。

我现在有

‘你确定吗?’,:method =>:delete%>

它会删除事件及其参与。 我需要另一个动作吗? 或者可以劫持事件的破坏行为? 它会是什么样子?

谢谢

嗯,在视图助手中,黑客可能是这样的:

 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(事件)来单独删除事件,并使用link_to_delete_event(事件,参与)来删除参与。 你的控制器可能是这样的:

 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