Rails 关于 Rails 如何来初始化数据库

shangrenzhidao · 2014年11月06日 · 最后由 cifery 回复于 2014年11月06日 · 3277 次阅读

Agile Rails 上的一个练习,现在有这样一个需求,应用安装以后需要初始化管理员,因为表中没有数据,所以允许第一个用户可以使用任意用户名登录,然后再创建管理员。 我的思路是: 1.在 session controller 中加个判断,如果 User.count.zero? 满足,则 使用创建这个用户,但是 Rails 4 中有一个 strong parameter 概念,这个方法定义到了 users_controller 中,我有必要再一次在 session controller 中添加这个方法?有没有办法可以把其他 controller 中私有方法直接拿来使用。

  1. 假设我在 session controller 又加了这个 strong parameter 的方法,我需要在 session 加入判断 User.count.zero? 但程序并没有执行这个判断。求赐教。

这是书上的原话 : When the system is freshly installed on a new machine, there are no administrators defined in the database, and hence no administrator can log on. But, if no administrator can log on, then no one can create an administrative user. Change the code so that if no administrator is defined in the database, any username works to log on (allowing you to quickly create a real administrator).

lass SessionsController < ApplicationController
  skip_before_action :authorize
  def new
  end

  def create
    if User.count.zero?  ### 没有执行!
      user =  User.create(user_params)
      session[:user_id] = user.id
      redirect_to admin_url
    else
      user = User.find_by(name: params[:name])
      if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to admin_url
      else
        redirect_to login_url, alert: 'Invalid user/password combination'
      end
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to store_url, notice: 'Logged out'
  end

  private
    def init
    end

    def user_params
      params.permit(:name, :password, :password_confirmation)
    end
end

这些判断不能写到 config/initializers 里面么

unless User.where(name: 'admin').exists?
  User.new(name: 'admin', password: '123456', password_confirmation: '123456').save
end

关于 Rails 如何来初始化数据库

直接回答是 Migrations and Seed Data http://guides.rubyonrails.org/migrations.html#migrations-and-seed-data

顶楼思路我觉得不是好思路,不回答。

可以把 APP 需要的初始数据,写在 db/seeds.rb 文件里,然后跑 rake db:seed 加载到数据库里面去。

例如:

country_list = [
  [ "Germany", 81831000 ],
  [ "France", 65447374 ],
  [ "Belgium", 10839905 ],
  [ "Netherlands", 16680000 ]
]

country_list.each do |name, population|
  Country.create( name: name, population: population )
end

#1 楼 @ywjno 我只想在程序中判断,而且不能写死。也就是第一个访问网站的用户可以登录。

也就是 users 表为空的时候任何一个人都可以登陆然后到管理界面添加管理员,既然要这样的话干嘛非要登陆呢?能不能考虑改成当 users 表为空的时候,admin_path 可以随意访问呢?

#5 楼 @cifery 个人觉得这个需求很牵强,谢谢。不想考虑这个问题了。意义不大

#5 楼 @cifery 个人觉得这个需求很牵强,谢谢。不想考虑这个问题了。意义不大

需要 登录 后方可回复, 如果你还没有账号请 注册新账号