我正在尝试在 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]
但这应该是正确的,对吧?我猜 key 将由 Contest.rb :before_create 回调添加?
也许我错过了使用 SecureRandom?
最佳答案
为什么使用attr_accessor
?该方法实际上将为键定义 setter 和 getter 方法,以跟踪虚拟属性。
也许您打算使用 attr_accessible
,但即便如此,这也是不必要的,因为您是直接设置属性。
真的,如果您只是像这样设置,那么您的模型中根本不需要 attr_accessor :key
或 attr_accessible :key
。删除 attr_accessor
即可正常工作。
关于ruby-on-rails - rails :before_create callback not working for my Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9299647/