0

有几个问题可以解决非常相似的问题,但是我误解了解决方案或提问者的情况存在细微差别。

该属性confirmed受到保护,因此我无法批量分配它。经过研究,似乎以下解决方案应该有效。我可以同时查看token(也受保护的)和confirmed闪存中的,但我无法在其下方设置“已确认”。我究竟做错了什么?

  if !@user.confirmed && params[:token] == @user.token
    flash[:success] = @user.token, @user.confirmed
    @user.confirmed = true
    @user.save
  end

谢谢阅读!

4

2 回答 2

1

我已经在我的一个测试应用程序中复制了您的场景,并且可以将已发布(在您的情况下已确认)设置为 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

有时将有效的代码与无助于识别问题的代码进行比较,这就是这个答案背后的意图。

希望这可以帮助您识别问题。

于 2013-02-15T05:38:07.110 回答
0

将这些属性添加到模型中的 attr_accessible。

并阅读此内容以获取详细信息: http ://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

于 2013-02-14T07:45:45.613 回答