为电子邮件确认路由分配受保护的属性

时间:2013-02-14 06:45:54

标签: ruby-on-rails ruby-on-rails-3 protected

有几个问题可以解决非常类似的问题,但要么我误解了解决方案,要么在提问者的情况下有些细微差别。

属性confirmed受到保护,因此我无法批量分配它。在研究之后,似乎以下解决方案应该起作用。我可以在flash中查看token(也受保护)和confirmed,但我无法在下面设置“已确认”。我做错了什么?

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

感谢阅读!

2 个答案:

答案 0 :(得分: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

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

希望这可以帮助您找出问题。

答案 1 :(得分:0)

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

阅读本文以获取详细信息: http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html