【问题标题】:Adding only devise :confirmable to a Model仅添加设计 :confirmable 到模型
【发布时间】:2013-04-21 00:26:14
【问题描述】:

我需要向 Rails 应用程序中的模型添加确认电子邮件功能,但没有别的。它不是一个用户模型,它是不可验证的。

我在模型中添加了devise :confirmable,并运行了迁移:

class AddConfirmableToProjects < ActiveRecord::Migration
  def up
    add_column :projects, :confirmation_token, :string
    add_column :projects, :confirmed_at, :datetime
    add_column :projects, :confirmation_sent_at, :datetime
    add_index :projects, :confirmation_token, :unique => true
  end

  def down
    remove_column :projects, :confirmation_token, :confirmed_at, :confirmation_sent_at
  end
end

但是当我创建一个新项目时,我得到:Could not find a valid mapping for #&lt;Project...

【问题讨论】:

标签: ruby-on-rails ruby devise devise-confirmable


【解决方案1】:

将 :confirmable 添加到不是您的用户模型的模型听起来有点奇怪。你确定吗?

# Confirmable is responsible to verify if an account is already confirmed to
# sign in, and to send emails with confirmation instructions.

如果,这是在运行规范/测试后返回的错误吗?如果您使用 RSpec 运行 FactoryGirl,请尝试在 test.rb 文件中添加 config.cache_classes = true。这有点可疑,但看起来是唯一的解决方案。

如果,请提供更多代码(模型、控制器、视图)。

【讨论】:

  • 我想这样做来验证用户的电子邮件地址:人们可以将某些内容上传到应用程序,但他们需要在这样做后确认他们的电子邮件。仅一次。在正常情况下它会失败,没有 rspec。
【解决方案2】:

是的,我们可以为任何型号设置可确认的。以下是执行此操作的步骤。假设我有一个模型 Invitation:

  1. devise :confirmable 添加到Invitation
  2. 这个模型应该有属性:email
  3. 使用以下列创建迁移:

    t.string   "email"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    
  4. 创建一个需要扩展Devise::ConfirmationsController 的控制器。在该控制器中添加以下代码:

    def create
      self.resource = resource_class.send_confirmation_instructions(params[resource_name])
      if successful_and_sane?(resource)
        respond_with({}, :location => root_url)
      else
        # code your logic
      end
    end
    
    def new; end
    
    def show; end
    
    • 在“app/views/devise/mailer/”下创建电子邮件视图confirmation_instruction.html.erb

    • 以下行将在您的电子邮件中创建确认 URL:&lt;%= confirmation_url(@resource, :confirmation_token =&gt; @resource.confirmation_token) %&gt;

    • 现在通过Invitation.create(:email =&gt; params[:email]为您的模型“邀请”创建新记录

    • 现在成功创建后,记录将保存在数据库中,电子邮件也将发送到该电子邮件。

【讨论】:

    猜你喜欢
    • 2011-06-14
    • 2016-10-11
    • 1970-01-01
    • 2016-09-03
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多