Rails - 未更改的属性已注册为已更改?

时间:2016-09-19 01:45:36

标签: ruby-on-rails ruby activerecord callback

Order has_many RentalItems

所以我在Order上进行了回调,其中重点是当xyz_method RentalItemsize更改时,specification会运行,或者已添加新的孩子RentalItem

before_save do
  if rental_items_attributes_modified?
    xyz_method
  end
end

def rental_items_attributes_modified?
  self.rental_items.each do |ri|
    # as long as ONE item had ONE thing changed, we return true or it's a new record
    puts "in RI modified?"
    puts "#{ri.new_record?} with ID #{ri.id}"
    puts "#{ri.specification_changed?} from #{ri.specification_was} to #{ri.specification}"
    puts "#{ri.size_changed?} from #{ri.size_was} to #{ri.size}"
    if ri.specification_changed? || ri.size_changed? || ri.new_record?
      return true
    end
  end
  return false
end

所有puts都在帮助我调试...我不知道为什么但是rental_items_attributes_modified?仍然保持正确,因为对于RentalItems中的一个,specification_changed?会返回true即使它不是......这是相关的日志输出:

# testing the first child RI
in RI modified?
false with ID 1
false from blue to blue
false from Regular to Regular

# testing the second child RI
in RI modified?
false with ID 2
true from  to # <<< why is this happening???
false from Regular to Regular

对于有问题的第二个孩子RI,最初specification = "",以及传递的内容是这样的参数:

"rental_items_attributes"=>[{"id"=>"2", "specification"=>"", "size"=>"Regular"}]

我在控制台中尝试过这个独立程序,它会触发正确的行为......

# for an order whose child RI initially had a blank specification & size
o.update_attributes({"rental_items_attributes" => [{"id" => 79, "specification" => ""}]})
=>
in RI modified?
false with ID 79
false from  to 
false from  to 

1 个答案:

答案 0 :(得分:0)

这只是一个评论,但由于声誉较低,我无法发表评论。 (因此,您可以忽略此评论。)

你有没有检查过before_save块中的值?像,

ri.specification_was.nil?
ri.specification.nil?

两者都是假的?