gpt4 book ai didi

ruby-on-rails - Rails after_create 回调无法访问模型的属性

转载 作者:行者123 更新时间:2023-12-03 16:03:06 24 4
gpt4 key购买 nike

我无法在 after_create 回调中访问我的模型的属性......似乎我应该能够对吗?

Controller :

@dog = Dog.new(:color => 'brown', :gender => 'male')
@dog.user_id = current_user.id
@dog.save

模型:
class Dog < ActiveRecord::Base
def after_create
logger.debug "[DOG CREATED] color:#{color} gender:#{gender} user:#{user_id}"
end
end

控制台:(一切似乎都很好)
>>Dog.last
=>#<Dog id: 1, color: "brown", gender: "male", user_id: 1>

日志:(哇!?)
...
[DOG CREATED] color: gender:male user
...

我的一些属性显示出来,而另一些则没有!不好了!有谁知道我做错了什么?过去,我一直能够以这种方式使用 after_create。

注意:我实际使用的变量名和值不同,但是方法和代码是一样的。

最佳答案

想通了我自己的问题。

其中一个属性是虚拟属性,我在其中使用了 self.update_attribute...哎呀!

def price=(amt)
self.update_attribute(:price_in_cents, (amt*100.0).to_i)
end

因此,对于记录,update_attribute 将实际创建数据库记录(并触发 after_create),如果它还没有被创建。

下次我一定会发布完整的代码!

关于ruby-on-rails - Rails after_create 回调无法访问模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2594078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com