如何在Rails中的before_destroy回调中访问params

时间:2014-11-10 15:37:32

标签: ruby-on-rails

如何为以下控制器编写before_destroy回调函数:

class RelationshipsController < ApplicationController
   ....

   def destroy
      @user = Relationship.find(params[:id]).followed
      current_user.unfollow(@user)
      respond_to do |format|
         format.html { redirect_to @user }
         format.js
      end
   end
end

class Relationship < ActiveRecord::Base
    belongs_to :follower, class_name: "User"
    belongs_to :followed, class_name: "User"
    validates :follower_id, presence: true
    validates :followed_id, presence: true
    before_destroy :delete_car_permissions 

    private

    def delete_car_permissions
       car_ids = followed.car_ids
       Permission.where("thing_id IN (?) AND user_id = ?", car_ids, follower).delete_all
    end
end

delete_car_permissions无法正常工作,因为我无法访问模型中的params!

1 个答案:

答案 0 :(得分:0)

您不需要params[:id]来标识Relationship,因为before_destroy回调在实例上运行,而不是在类上运行。

这就足够了:

    def delete_car_permissions
        car_ids = followed.car_ids
        Permission.where("thing_id IN (?) AND user_id = ?", car_ids, follower).delete_all
    end