我正在阅读 Michael Hartl 的教程并有一个 sample_data.rake 文件。当我尝试填充数据库时,我收到“无法批量分配受保护的属性:管理员”错误。我可以通过在“user.rb”文件中将“:admin”添加到“attr_accessible”来修复它,但是这样任何人都可以破解自己的方式成为管理员。我该如何解决这个问题?
sample_data.rake 文件
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
admin = User.create!(name: "Example User",
email: "example@railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true)
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
end
end
用户.rb 文件
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
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 :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
谢谢你的帮助!我是一个完整的初学者,所以请保持简单。