我已经在我的一个测试应用程序中复制了您的场景,并且可以将已发布(在您的情况下已确认)设置为 true。
移民
def up
create_table :posts do |t|
t.string :title
t.boolean :published, :default => false
t.string :token
t.timestamps
end
模型
class Post < ActiveRecord::Base
attr_protected :published
before_create :generate_token
def generate_token
self.token = Time.now().to_i
end
end
控制器
class PostsController < ApplicationController
def publish
@post = Post.find_by_token(params[:token])
if !@post.published && params[:token] == @post.token # The second condition is not necessary in this case.
@post.published = true
@post.save
end
end
end
创建数据库记录表单控制台
1.9.3-p0-perf :001 > p = Post.new({:title => "Protests against Violence"})
=> #<Post id: nil, title: "Protests against Violence", published: false, token: nil, created_at: nil, updated_at: nil>
1.9.3-p0-perf :002 > p.save
(0.2ms) BEGIN
SQL (7.3ms) INSERT INTO "posts" ("created_at", "published", "title", "token", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Thu, 14 Feb 2013 07:41:58 UTC +00:00], ["published", false], ["title", "Protests against Violence"], ["token", 1360827718], ["updated_at", Thu, 14 Feb 2013 07:41:58 UTC +00:00]]
(7.5ms) COMMIT
=> true
1.9.3-p0-perf :003 > p.reload
Post Load (1.2ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT 1 [["id", 2]]
=> #<Post id: 2, title: "Protests against Violence", published: false, token: "1360827718", created_at: "2013-02-14 07:41:58", updated_at: "2013-02-14 07:41:58">
点击 /publish/1360827718 后 - 这是控制台的输出
#<Post id: 2, title: "Protests against Violence", published: true, token: "1360827718", created_at: "2013-02-14 07:41:58", updated_at: "2013-02-14 07:45:33">
我正在使用 postgresql、rails 3.2.11 和 ruby 1.9.3 运行此代码,并且控制器中的发布操作设置了 published=true
有时将有效的代码与无助于识别问题的代码进行比较,这就是这个答案背后的意图。
希望这可以帮助您识别问题。