我正在构建一个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>'
任何帮助将不胜感激。谢谢:)
答案 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
的更多信息