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%>

イベントとその参加の両方を削除します。別のアクションが必要ですか?または、イベントの破壊アクションを乗っ取ることができますか?それはどのように見えるでしょうか?

ありがとう

4

1 に答える 1

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( event )を使用し、参加を削除するには link_to_delete_event( event, registration )を使用します。コントローラーは次のようになります。

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 に答える