【问题标题】:Rails 5: ActiveRecord not creating recordRails 5:ActiveRecord 不创建记录
【发布时间】:2016-10-21 01:43:55
【问题描述】:

我正在编写 Michael Hartl 的 Learn Rails 教程的修改版本。我在第 6 章,为用户建模。出于某种原因,我的用户没有在 ActiveRecord 上正确创建并且根本没有保存。

我将这些用户放在我的seeds.rb 文件中

user_1 = User.create(id: 1, name: 'Han Solo', email: 'han@example.com')
user_2 = User.create(id: 2, name: 'Luke Skywalker', email: 'luke@example.com')

然后我运行rails db:seed,但如果我转到我的rails console,似乎没有创建用户:

Running via Spring preloader in process 24358
Loading development environment (Rails 5.0.0.1)
2.2.2 :001 > User.delete_all
  SQL (1.1ms)  DELETE FROM "users"
 => 0 
2.2.2 :002 > 

user.rb 用户模型

class User < ApplicationRecord
    #Ensure Email Uniqueness by Downcasing the Email Attribute
    before_save {self.email = email.downcase }
    #validates name, presence, and length
    validates :name, presence: true, length: { maximum: 100 }
    #Validate presence, length, format, and uniqueness (ignoring case)
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: {maximum: 250}, format: {with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false}
    #Adds ability to save securely hashed password_digest attribute to database
    #Adds a pair of virtual attributes (password and password_confirmation)
    #including presence validations upon object creation and a validation
    #requiring that they match
    #adds authenticate method that returns the user when the password is correct (and false otherwise)
    has_secure_password
    PASSWORD_FORMAT = /\A
        (?=.{8,})          # Must contain 8 or more characters
        (?=.*\d)           # Must contain a digit
        (?=.*[a-z])        # Must contain a lower case character
        (?=.*[A-Z])        # Must contain an upper case character
        (?=.*[[:^alnum:]]) # Must contain a symbol
    /x
    validates :password, presence: true, length: {minimum: 8}, format: {with: PASSWORD_FORMAT}

end

schema.rb

ActiveRecord::Schema.define(version: 20161020211218) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "password_digest"
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
  end

end

有人知道会发生什么吗?

【问题讨论】:

  • 您的数据库中是否已有该用户?当您检查 valid? 时会出现它返回 false,因为该电子邮件地址已被使用。
  • 请使用 IANA 沙箱域 @example.com 而不是真实的 gmail 地址作为示例。它可以防止拥有该地址的人被垃圾邮件机器人收割。
  • 在调用user.valid? 之后调用user.errors.full_messages 看看是什么阻止了同样的事情。
  • 我想您可能对user.valid? 行感到困惑。 =&gt; false .valid? 方法调用的返回值——不是数据库查询。
  • 嘿,看看我刚刚更新的代码,当我运行 rails db:seed 然后运行 ​​rails console 和 User.delete_all 以删除我刚刚创建的用户时,它们似乎不存在。

标签: ruby-on-rails ruby activerecord ruby-on-rails-5


【解决方案1】:

好的,我想通了。

  1. 我从seeds.rb 中取出了id。当我取出 id 属性时,它开始向我抛出用户没有有效密码的错误。然后我添加了密码和密码确认,以符合我的用户模型中设置的密码标准。
  2. 更新了我的模型并添加了密码确认。

这是我更新的user.rb

class User < ApplicationRecord
    #Ensure Email Uniqueness by Downcasing the Email Attribute
    before_save {self.email = email.downcase }
    #validates name, presence, and length
    validates :name, presence: true, length: { maximum: 100 }
    #Validate presence, length, format, and uniqueness (ignoring case)
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: {maximum: 250}, format: {with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false}
    #Adds ability to save securely hashed password_digest attribute to database
    #Adds a pair of virtual attributes (password and password_confirmation)
    #including presence validations upon object creation and a validation
    #requiring that they match
    #adds authenticate method that returns the user when the password is correct (and false otherwise)
    has_secure_password
    PASSWORD_FORMAT = /\A
        (?=.{8,})          # Must contain 8 or more characters
        (?=.*\d)           # Must contain a digit
        (?=.*[a-z])        # Must contain a lower case character
        (?=.*[A-Z])        # Must contain an upper case character
        (?=.*[[:^alnum:]]) # Must contain a symbol
    /x
    validates :password, presence: true, length: {minimum: 8}, format: {with: PASSWORD_FORMAT}
    validates :password_confirmation, presence: true
end

还有seeds.rb

user_1 = User.create!(name: 'Han Solo', email: 'han@example.com', password: 'Password123!', password_confirmation: 'Password123!')
user_2 = User.create!(name: 'Luke Skywalker', email: 'luke@example.com', password: 'Password123!', password_confirmation: 'Password123!')

我通过打开 rails 控制台、运行 User.delete_all 并看到他们从 SQL 记录中删除来测试是否正确创建了用户。

【讨论】:

  • 您永远不会为记录分配 ID - 数据库会自动增加 id 列,并将 id 作为 INSERT sql 查询的一部分返回。
  • 再次感谢您的再次确认!我会记住这一点的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-09
相关资源
最近更新 更多