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

时间:2011-07-26 14:08:22

标签: ruby-on-rails action destroy jointable

我有以下简单模型:

class Event < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations
end

class Participation < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :participations
  has_many :events, :through => :participations
end

我认为,根据当前用户角色,我想要删除事件及其参与记录,或者只删除参与记录。

我目前有

  

&lt;%= link_to'删除事件',事件,:confirm =&gt; '你确定吗?',   :method =&gt; :删除%&gt;

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

由于

1 个答案:

答案 0 :(得分:2)

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

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