【问题标题】:Deleting just a join table record in Ruby on Rails在 Ruby on Rails 中仅删除连接表记录
【发布时间】:2011-10-13 11:08:24
【问题描述】:

我有以下简单模型:

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

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

我现在有

'你确定吗?', :method => :delete %>

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

谢谢

【问题讨论】:

    标签: ruby-on-rails action destroy jointable


    【解决方案1】:

    好吧,在视图助手中,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
    

    【讨论】:

    • 非常感谢 Mauricio,我现在将使用此解决方案,但请保持问题未解决,以寻求不那么 hack 的解决方案。
    • 现在是一个简单的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多