我为问这样一个菜鸟问题而道歉,但我真的很困惑为什么这不起作用。我正在创建一个reddit克隆作为一种教自己的方式。创建新帖子时,我想将upvote和downvote属性设置为零。我做错了什么?
编辑:当我通过我的rails服务器创建一个新的Post
时看起来像before_save,但是在控制台中创建一个新的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
schema.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>