在这里生气。任何指针都感激不尽!
我有一个交付模型,我正在尝试根据交付行添加一种方法来更新交付状态。此函数在模型类中定义,delivery_state是模型属性之一:
def updateDeliveryState
expectedLines = DeliveryLine.where( :delivery_id => id,
:line_state => 'EXPECTED' )
logger.debug "State1: #{delivery_state}"
if expectedLines.length == 0
if delivery_state == 'EXPECTED' || delivery_state == 'RECEIVING'
delivery_state = 'RECEIVED' # commenting this line fixes it
save
end
else
logger.debug "State2: #{delivery_state}"
if delivery_state == 'EXPECTED'
logger.debug "Updating to receiving"
delivery_state = 'RECEIVING'
save
end
end
end
我在日志中看到的是在2 logger.debug
行之间,delivery_state已被清除:
State1: EXPECTED
DeliveryLine Load (4.5ms) SELECT "delivery_lines".* FROM "delivery_lines"
WHERE "delivery_lines"."line_state" = 'EXPECTED'
AND "delivery_lines"."delivery_id" = 227
State2:
如果我注释掉上面代码中标记的行,它似乎工作正常:
State1: EXPECTED
DeliveryLine Load (9.6ms) SELECT "delivery_lines".* FROM "delivery_lines"
WHERE "delivery_lines"."line_state" = 'EXPECTED'
AND "delivery_lines"."delivery_id" = 227
State2: EXPECTED
Updating to receiving
但是,刷新后我可以看到,在此之后交付仍然是预期的?
答案 0 :(得分:3)
详细说明我的评论:您似乎在if
中创建了一个局部变量。看:
class Foo
attr_accessor :bar
def test
unless bar
bar = 1
end
end
end
f = Foo.new
f.test
puts f.bar # empty line, bar is nil
现在让我们确保调用setter:
class Foo
attr_accessor :bar
def test
unless bar
self.bar = 1
end
end
end
f = Foo.new
f.test
puts f.bar # prints 1
请参阅:Why do ruby setters need “self.” qualification within the class?
答案 1 :(得分:0)
您可以尝试使用save(:validate => false)
吗?
有时候Rails有这种讨厌的习惯,即默默地验证失败而不是保存。
你可能想要保存你的状态,无论什么......:)