我試圖保存我的模型對象導軌時出現錯誤。讓我說,我沒有使用數據庫遷移,並使用預先存在的數據庫與軌道。 這裏是我的模型類: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