我试图保存我的模型对象导轨时出现错误。让我说,我没有使用数据库迁移,并使用预先存在的数据库与轨道。 这里是我的模型类:Rails的ActiveRecord保存错误未定义的方法'[]'为零:NilClass
require 'bcrypt'
require 'securerandom'
class Profile < ActiveRecord::Base
include BCrypt
self.table_name = 'profiles'
self.primary_key = 'id'
attr_accessor :id, :username, :password_hash, :salt, :first_name, :last_name, :location, :status, :game_status
def initialize(attributes = {}, options = {})
@username = attributes[:username]
@salt = SecureRandom.hex
@password_hash = Password.create(attributes[:password] + @salt).to_s
@first_name = attributes[first_name]
@last_name = attributes[last_name]
@location = attributes[location]
@status = "Hi"
@game_status = "Playing some game..."
end
def hash_rep
hash = {}
hash['id'] = @id
hash['username'] = @username
hash['password_hash'] = @password_hash
hash['salt'] = @salt
hash['location'] = @location
hash['status'] = @status
hash['game_status'] = @game_status
return hash
end
end
这里是我的数据库架构:
id int Unsigned NOT NULL AUTO_INCREMENT
username varchar(16) NOT NULL
password_hash tinytext NOT NULL
salt varchar(64) NOT NULL
first_name varchar(16) NOT NULL
last_name varchar(16) NOT NULL
location tinytext NOT NULL
status tinytext NULL
game_status tinytext NULL
这是我为我的控制器代码:
def register
profile = Profile.new(:id => params[:id],
:username => params[:username],
:password => params[:password],
:first_name => params[:first_name],
:last_name => params[:last_name],
:location => params[:location])
profile.save
render_profile(profile)
end
上的个人资料时发生错误。保存'方法。下面是相关堆栈跟踪:
activerecord (4.2.0) lib/active_record/transactions.rb:375:in `clear_transaction_record_state'
activerecord (4.2.0) lib/active_record/transactions.rb:306:in `ensure in rollback_active_record_state!'
activerecord (4.2.0) lib/active_record/transactions.rb:306:in `rollback_active_record_state!'
activerecord (4.2.0) lib/active_record/transactions.rb:285:in `save'
app/controllers/profile_controller.rb:52:in `register'
actionpack (4.2.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (4.2.0) lib/abstract_controller/base.rb:198:in `process_action'
错误说:“未定义的方法`[]”为无:NilClass”
有一个名为'params'在'register'没有局部变量。也就是说,局部变量'params'在第一次出现时被初始化为'nil'; 'params [:id]'在此相当于'nil [:id]'导致你得到的错误。 – mudasobwa
在控制台中逐步完成此操作:通过从日志中复制设置参数并逐行执行代码。你应该能够看到什么是不对的。 –
哎哟,你做了很多错误的东西:当它关于表列时,不需要attr_accessors,不要重新初始化 – apneadiving