Rails before_destory仅适用于destroy而不适用于删除

时间:2013-09-08 16:12:08

标签: ruby-on-rails filter before-filter

我正在构建一个rails应用程序,在其中的一部分,我保存到数据库,支付信息。我需要让这些付款不可删除。

我创建了一个有效的before_destroy函数..但我遇到了一个问题:

这是我的代码:

class StripePayment < ActiveRecord::Base
belongs_to :user
belongs_to :stripe_card

before_destroy :fail

private
def fail
    return false
end
end

当我创建付款并在删除时试用我的代码:

StripePayment.first.destroy返回false并回滚...这正是我想要的。

然而, StripePayment.first.delete传递并删除对象。

我知道删除和销毁之间的差别。但是,我希望能够阻止在数据库上删除此对象(在delete()destroy()来电。

我尝试before_delete并且rails给了我这个错误:

NoMethodError: undefined method `before_delete' for #<Class:0x007fc1abc37c50>
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:22:in `method_missing'
from /Users/alybadawy/developing/repos/finish/finish/app/models/stripe_payment.rb:7:in `<class:StripePayment>'
from /Users/alybadawy/developing/repos/finish/finish/app/models/stripe_payment.rb:1:in `<top (required)>'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:423:in `load'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:423:in `block in load_file'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:615:in `new_constants_in'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:422:in `load_file'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:323:in `require_or_load'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:462:in `load_missing_constant'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:183:in `const_missing'
from (irb):1
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /Users/alybadawy/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

任何帮助将不胜感激。谢谢:)

2 个答案:

答案 0 :(得分:2)

最简单的方法是,定义自己的删除方法

class StripePayment < ActiveRecord::Base
  belongs_to :user
  belongs_to :stripe_card

  before_destroy :fail

  def delete
    false
  end

  private
  def fail
      return false
  end
end

如果您有条件允许删除,可以使用删除方法检查并拨打super

答案 1 :(得分:1)

这是因为delete是跳过rails中回调的函数之一

请查看此主题,了解有关主题http://edgeguides.rubyonrails.org/active_record_callbacks.html#skipping-callbacks

的更多信息