2011-07-26 45 views
1

我有以下簡單的模型:刪除只是一個on Rails的連接表記錄在Ruby中

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 

編輯

爲了使它少一個黑客,你應該創建參股下事件嵌套資源:

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

現在是一個不好的解決方案。 –

相關問題