Rails:before_create 回调不适用于我的模型
我正在尝试在 Rails 3 模型中执行以下操作:
require 'securerandom'
class Contest < ActiveRecord::Base
attr_accessor :key
before_create :generate_key
private
def generate_key
self.key = SecureRandom.hex(3)
end
end
但是,当我创建竞赛时,表中的所有字段似乎都是正确的,除了数据库中保留为零的键之外。
更多信息:
在我的rails服务器日志中,当我通过“创建竞赛表单”创建竞赛时,我看到以下内容,
SQL (0.5ms) INSERT INTO "contests" ("category", "created_at", "description", "key", "price", "status", "time", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["category", "camisas"], ["created_at", Wed, 15 Feb 2012 18:57:16 UTC +00:00], ["description", "test_description"], ["key", nil], ["price", 111], ["status", "In process"], ["time", "2sem"], ["title", "test_contest"], ["updated_at", Wed, 15 Feb 2012 18:57:16 UTC +00:00], ["user_id", 5]]
请注意[“key”,nil]
但这应该是正确的,对吗?,我会猜测密钥将由 Contest.rb :before_create 回调添加吗?
也许我错过了使用 SecureRandom?
I'm trying to do the following in my Rails 3 model:
require 'securerandom'
class Contest < ActiveRecord::Base
attr_accessor :key
before_create :generate_key
private
def generate_key
self.key = SecureRandom.hex(3)
end
end
However when I create a Contest, all the fields in my table appear to be correct except the key which remains nil in my DB.
More Info:
In my rails server log, I see the following when I create a contest through my "create contest form"
SQL (0.5ms) INSERT INTO "contests" ("category", "created_at", "description", "key", "price", "status", "time", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["category", "camisas"], ["created_at", Wed, 15 Feb 2012 18:57:16 UTC +00:00], ["description", "test_description"], ["key", nil], ["price", 111], ["status", "In process"], ["time", "2sem"], ["title", "test_contest"], ["updated_at", Wed, 15 Feb 2012 18:57:16 UTC +00:00], ["user_id", 5]]
Note the ["key", nil]
But that should be correct right?, I would guess that the key will be added by the Contest.rb :before_create callback?
Maybe I'm miss-using SecureRandom?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么使用
attr_accessor
?该方法实际上将为键定义 setter 和 getter 方法,以跟踪虚拟属性。也许您打算使用
attr_accessible
,但即便如此,这也是不必要的,因为您是直接设置属性。实际上,如果您只是像这样设置,那么您的模型中根本不需要
attr_accessor :key
或attr_accessible :key
。删除attr_accessor
,它就可以工作了。Why are you using
attr_accessor
? This method is actually going to be defining both a setter and getter method for a key, keeping track of a virtual attribute.Perhaps you meant to use
attr_accessible
, but even then that is unnecessary, because you're setting the attribute directly.Really, you don't need either
attr_accessor :key
orattr_accessible :key
in your model at all if you're just setting it like this. Remove theattr_accessor
and it will work.我认为你应该写
attr_accessible
例如:attr_accessible :键,:类别
I think you should write
attr_accessible <list accessible params>
for example:attr_accessible :key, :category