Ruby on rails 对'的有条件行动;更新前';行动

Ruby on rails 对'的有条件行动;更新前';行动,ruby-on-rails,Ruby On Rails,只有在更新数据库时,某些条件或方法返回true时,我才需要调用update操作。我怎么做 我试过: before_update :check_loan_status ,if: ->{} 即使条件语句返回false,也会调用update方法。您可以这样做 class Post < ApplicationRecord after_update :call_me,:if => Proc.new { |obj| obj.id == obj.id } before_update

只有在更新数据库时,某些条件或方法返回
true
时,我才需要调用
update
操作。我怎么做

我试过:

before_update :check_loan_status ,if: ->{}

即使条件语句返回
false

,也会调用
update
方法。您可以这样做

class Post < ApplicationRecord
  after_update :call_me,:if => Proc.new { |obj| obj.id == obj.id }
  before_update :call_me,:if => Proc.new { |obj| obj.id == obj.id }

  def call_me
    puts "condition is true"
  end
end
class PostProc.new{{| obj | obj.id==obj.id}
在更新之前:调用我,:if=>Proc.new{{| obj | obj.id==obj.id}
打电话给我
将“条件为真”
结束
结束

您可能应该使用语法“after\u update:call\u me,if:Proc.new…”冒号而不是fat arrow。@xploshioOn冒号可能不适用于旧版本的Ruby,而fat arrow适用于大多数版本(可能全部)。所以,当我不确定其他人使用的是什么Ruby版本时,我建议使用fat arrow。你是对的,让我们更具体一点,如果你使用Ruby 1.9或更高版本,请使用冒号而不是fat arrow。@xploshioOn但不要过于夸张地使用fat arrow vs colon。@xploshioOn我与Mongoid合作过很多次,Band.where(:fans.gt=>100000)将工作,而Band.where(fans.gt:100000)将不工作。