我很抱歉提出这样一个菜鸟问题,但我真的很困惑为什么这不起作用。我正在创建一个 reddit 克隆作为自学 Rails 的一种方式。创建新帖子时,我想将 upvote 和 downvote 属性设置为零。我究竟做错了什么?
编辑:当我通过我的 Rails 服务器创建一个新的时,它看起来像 before_save 工作,但在控制台中Post
创建一个新的时它不起作用。Post
为什么是这样?
post.rb
class Post < ActiveRecord::Base
attr_accessible :title, :url, :upvotes, :downvotes
before_save :set_votes_to_zero
def set_votes_to_zero
self.upvotes = 0
self.downvotes = 0
end
end
架构.rb
ActiveRecord::Schema.define(:version => 20121223192629) do
create_table "posts", :force => true do |t|
t.string "title"
t.string "url"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "upvotes"
t.integer "downvotes"
end
end
创建新帖子时的 Rails 控制台输出
irb(main):035:0> Post.create(title: "Facebook", url: "www.facebook.com")
←[1m←[35m (0.0ms)←[0m begin transaction
←[1m←[36mSQL (0.0ms)←[0m ←[1mINSERT INTO "posts" ("created_at", "downvotes",
"title", "updated_at", "upvotes", "url") VALUES (?, ?, ?, ?, ?, ?)←[0m [["creat
ed_at", Sun, 23 Dec 2012 19:43:37 UTC +00:00], ["downvotes", nil], ["title", "Fa
cebook"], ["updated_at", Sun, 23 Dec 2012 19:43:37 UTC +00:00], ["upvotes", nil]
, ["url", "www.facebook.com"]]
←[1m←[35m (124.8ms)←[0m commit transaction
=> #<Post id: 9, title: "Facebook", url: "www.facebook.com", created_at: "2012-1
2-23 19:43:37", updated_at: "2012-12-23 19:43:37", upvotes: nil, downvotes: nil>