2011-07-26 9 views
1

I持って、次の単純なモデル:私は私の見解でやりたい何の削除だけではRuby on Railsでテーブルレコードに参加

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を持っている、:確認=> 'あなたはよろしいですか?'、 :メソッド=>:削除%>

イベントとその参加の両方を削除します。別の行動が必要ですか?またはイベントの破壊行為をハイジャックすることができますか?それはどのように見えるでしょうか?

おかげ

答えて

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 

あなたはイベントの下の参加のためのネストされたリソースを作成する必要がありハックのことが少ないようにするにEDIT

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 
+0

多くのおかげマウリシオは、私は今のところ、このソリューションを使用しますが、ハックの少ない解決するためのビットのためのオープンな質問をしておこう。 – pingu

+0

そして今はハックのない解決策です。 –

関連する問題