1

我有以下简单模型:

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

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

我目前有

<%= link_to '删除事件', event, :confirm => '你确定吗?', :method => :delete %>

这将删除事件及其参与。我需要采取其他措施吗?或者可以劫持Event的破坏动作?它会是什么样子?

谢谢

4

1 回答 1

2

好吧,在视图助手中,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
于 2011-07-26T14:15:05.533 回答