【问题标题】:Getting "ActiveRecord::UnknownAttributeError: unknown attribute: email_confirmation" Error with rspec使用 rspec 获取“ActiveRecord::UnknownAttributeError:未知属性:email_confirmation”错误
【发布时间】:2013-04-09 15:55:06
【问题描述】:

我在运行测试时遇到了这个错误。我已经检查以确保所有email_confirmations 拼写正确并且(除非我疯了)它们是正确的。我是一个 Rails 菜鸟,所以它可能很简单。

用户模型

class User < ActiveRecord::Base
  attr_accessible :email, :email_confirmation, :first_name, :last_name,
                  :password, :password_confirmation
  has_secure_password

  before_save { |user| user.email = email.downcase }

  validates :first_name, presence: true, length: { maximum: 25 }
  validates :last_name, presence: true, length: { maximum: 25 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  validates :email_confirmation, presence: true
  validates :password, presence: true, length: { maximum: 6 }
  validates :password_confirmation, presence: true
end

Rspec 测试

require 'spec_helper'

describe User do
  before { @user = User.new(email: "user@example.com",
                            first_name: "John", last_name: "Smith",
                            password: "foobar", password_confirmation: "foobar",
                            email_confirmation: "user@example.com") }

  subject { @user }

  it { should respond_to(:first_name) }
  it { should respond_to(:last_name) }
  it { should respond_to(:email) }
  it { should respond_to(:email_confirmation) }
  it { should respond_to(:password_digest) }
  it { should respond_to(:password) }
  it { should respond_to(:password_confirmation) }
  it { should respond_to(:authenticate) }

  it { should be_valid }

  describe "when first name is not present" do
    before { @user.first_name = " " }
    it { should_not be_valid }
  end

  describe "when last name is not present" do
    before { @user.last_name = " " }
    it { should_not be_valid }
  end

  describe "when email is not present" do
    before { @user.email = @user.email_confirmation = " " }
    it { should_not be_valid }
  end

  describe "when password is not present" do
    before { @user.password = @user.password_confirmation = " " }
    it { should_not be_valid }
  end

  describe "when first_name is too long" do
    before { @user.first_name = "a" * 26 }
    it { should_not be_valid }
  end

  describe "when last_name is too long" do
    before { @user.last_name = "a" * 26 }
    it { should_not be_valid }
  end

  describe "when email format is invalid" do
    it "should be invalid" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo.
                             foo@bar_baz.com foo@bar+baz.com]
      addresses.each do |invalid_address|
        @user.email = invalid_address
        @user.should_not be_valid
     end      
    end
  end

  describe "when email format is valid" do
    it "should be valid" do
      addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn]
      addresses.each do |valid_address|
        @user.email = valid_address
        @user.should be_valid
      end      
    end
  end

  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.email = @user.email.upcase
      user_with_same_email.save
    end

    it { should_not be_valid }
  end

  describe "when password doesn't match confirmation" do
    before { @user.password_confirmation = "mismatch" }
    it { should_not be_valid }
  end

  describe "when email doesn't match confirmation" do
    before { @user.email_confirmation = "mismatch@example.com" }
    it { should_not be_valid }
  end

  describe "when password confirmation is nil" do
    before { @user.password_confirmation = nil }
    it { should_not be_valid }
  end

  describe "when email confirmation is nil" do
    before { @user.email_confirmation = nil }
    it { should_not be_valid }
  end

  describe "with a password that's too short" do
    before { @user.password = @user.password_confirmation = "a" * 5 }
    it { should be_invalid }
  end

  describe "return value of authenticate method" do
    before { @user.save }
    let(:found_user) { User.find_by_email(@user.email) }

    describe "with valid password" do
      it { should == found_user.authenticate(@user.password) }
    end

    describe "with invalid password" do
      let(:user_for_invalid_password) { found_user.authenticate("invalid") }

      it { should_not == user_for_invalid_password }
      specify { user_for_invalid_password.should be_false }
    end
  end
end

schema.rb

ActiveRecord::Schema.define(:version => 20130417021135) do

  create_table "users", :force => true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
    t.string   "password_digest"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true

end

【问题讨论】:

  • 您可以为支持此模型的表粘贴您的数据库架构吗?
  • 用它编辑了帖子
  • 谢谢。 Rails 支持内置确认验证,请参阅下面的建议。

标签: ruby-on-rails validation


【解决方案1】:

您收到UnknownAttributeError 是因为您的users 表中没有名为email_confirmation 的列。默认情况下,ActiveRecord 将查找与您用于构建模型的属性名称相同的 DB 列,但此行尝试使用数据库不知道的属性来构建用户:

  before { @user = User.new(email: "user@example.com",
                        first_name: "John", last_name: "Smith",
                        password: "foobar", password_confirmation: "foobar",
                        email_confirmation: "user@example.com") }

您真的打算将电子邮件确认保存在数据库中,还是只是想在保存之前检查它是否与电子邮件匹配?我假设是后者,Rails 实际上已经内置支持这样做:

class User < ActiveRecord::Base
  validates :email, :confirmation => true
  validates :email_confirmation, :presence => true
end

查看Rails Guide to Validationsvalidates_confirmation_of API 文档的更多详细信息。 (你可能需要为:password_confirmation 做同样的事情。)

【讨论】:

  • 我遇到了同样的问题。数据库模式是问题所在(我认为是迁移)。谢谢!
  • 有时迁移尚未在特定环境中完成。像rake RAILS_ENV=production db:migrate 这样的命令可以解决问题。
  • 如果您修改了架构,您也可以尝试删除 cookie
【解决方案2】:

我知道上面的答案被标记为正确并解决了 OP 的问题。但是这个错误还有另一个原因,在关于这个主题的许多 stackoverflow 帖子中都没有引起注意。当您忘记对 has_many 使用 as: 选项时,此错误可能发生在多态多态中。例如:

class AProfile < ActiveRecord::Base
  has_many :profile_students
  has_many :students, through: :profile_students
end

class BProfile < ActiveRecord::Base
  has_many :profile_students
  has_many :students, through: :profile_students
end

class ProfileStudent < ActiveRecord::Base
  belongs_to :profile, polymorphic: :true
  belongs_to :student
end

class Student < ActiveRecord::Base
  has_many :profile_students
  has_many :aprofiles, through: :profile_students
  has_many :bprofiles, through: :profile_students
end

这会给你这个错误:

Getting “ActiveRecord::UnknownAttributeError: unknown attribute: profile_id

当您尝试执行以下操作时:

a = AProfile.new
a.students << Student.new

解决方法是在 AProfile 和 BProfile 中添加 :as 选项:

class AProfile < ActiveRecord::Base
  has_many :profile_students, as: :profile
  has_many :students, through: :profile_students
end

class BProfile < ActiveRecord::Base
  has_many :profile_students, as: :profile
  has_many :students, through: :profile_students
end

【讨论】:

    【解决方案3】:

    我有相同的消息错误,我修复了将参数排序为数据库中列定义的相同顺序:

    控制器

    def create
        worktime = Worktime.create(name: params[:name], workhours: params[:workhours], organization: @organization, workdays: params[:workdays])
    
        render json: worktime
    end
    

    数据库

    Table: worktimes
    Columns:
    id  int(11) AI PK
    name    varchar(255)
    workhours   text
    organization_id int(11)
    workdays    text
    

    【讨论】:

    • 我有 99.999% 的把握,无论您遇到什么问题,都无法通过按特定顺序排列参数来解决。如果是这样,那么还有其他事情在起作用。
    【解决方案4】:

    刚刚花了很多时间调试我自己的这个实例,我想我会加入第三种可能性。

    我已正确完成迁移并通过在 rails 控制台中检查我的ActiveRecord 来验证它。我曾多次尝试从架构中重新创建数据库,并且多次尝试重新运行迁移,但均无济于事。

    就我而言,问题是我在运行单元测试时发现了问题,而不是在运行时。问题是我的测试数据库在我的迁移/回滚测试中不同步。解决方案非常简单。我所要做的就是重置测试数据库:

    rake db:test:prepare
    

    【讨论】:

    • 好收获。我的情况有点不同。我在 Rails 5.0.0.1 中有 SQL 模式格式,我做了一次 db:rollback 和一次 db:migrate 。在回滚和迁移之间,我修改了最后一个数据库迁移文件。如edgeguides.rubyonrails.org/… 中所述,不建议使用此模式,但在早期开发中可能会很方便。我真的不知道如何或为什么,但生成的 structure.sql 模式对我来说是个问题,我不得不删除它并再次运行 db:migrate。
    • 这是对答案的一个很好的补充。像宣传的那样工作!
    • 这一直失败,直到我指定要测试的环境rake db:test:prepare RAILS_ENV=test
    【解决方案5】:

    我遇到了同样的问题,这就像魔术一样。在要更新的每个模型的迁移语句末尾添加此行。重置有关列的所有缓存信息,这将导致它们在下一次请求时重新加载。

        <ModelName>.reset_column_information
    

    参考:https://apidock.com/rails/ActiveRecord/Base/reset_column_information/class

    【讨论】:

      【解决方案6】:

      当表格没有列时,我多次遇到此错误,但这次我遇到了奇怪的原因。出于某种原因,我的迁移很完美,但(奇怪的是)schema.rb 没有更新,所以rake db:migrate db:seed 没有创建该列。我不知道为什么会这样。

      TL;DR,如果您的迁移是最新的,请检查 schema.rb 并确保它也是最新的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-10
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        相关资源
        最近更新 更多