【问题标题】:Rails user authentication: can you hardcode a user?Rails 用户身份验证:您可以对用户进行硬编码吗?
【发布时间】:2016-01-24 21:17:13
【问题描述】:

我有一个带有用户身份验证的工作 Rails 应用程序。我想自动对我的帐户进行编码,因为我将拥有管理员角色,而其他人都不会。有没有办法做到这一点?

顺便说一下,我的 db/migrate 表如下所示:

class CreateUsers < ActiveRecord::Migration
    def change
        create_table :users do |t|
            t.string :first_name
            t.string :last_name
            t.string :email
            t.string :password_digest
            t.string :role, default => 'reader'
            t.timestamps null: false
        end
    end
end

【问题讨论】:

  • 通过控制台将您的记录粘贴到数据库中?你也可以做一个 rake 任务或迁移

标签: ruby-on-rails authentication dbmigrate hardcode


【解决方案1】:

添加创建特定用户 (User.create(...)) 的迁移(例如使用 rails generate migration AddAdmin)。

【讨论】:

    【解决方案2】:

    我认为最好的方法是使用 seed 在 rails 2.3.4 中添加的功能

    db/seeds.rb
    

    在种子文件中添加您的代码,例如:User.create(...) 并运行 rake db:seed

    【讨论】:

      【解决方案3】:

      你可以这样写一个方法:

      class CreateUsers < ActiveRecord::Base
        def self.create_admin
        create(first_name:"xxx",last_name:"xxx",email:"xxx",password:"xxxx",
          role:"admin")
        end
      end
      

      然后你在rails控制台中运行这个方法

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-26
        • 1970-01-01
        • 2011-01-28
        • 2022-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多