我正在使用ruby(但不是rails)的活动记录。我正在使用sqlite3,它在文件上有一个test.db(不仅仅是在内存中)。当我使用user.create运行以下代码片段时,它会抱怨参数错误(当我使用use.save时,它会抛出一个活动记录异常。任何想法我可能做错了什么?谢谢
require 'rubygems'
gem 'activerecord'
require 'sqlite3'
require 'active_record'
ActiveRecord::Base.logger = Logger.new(STDERR)
#ActiveRecord::Base.colorize_logging = false
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:host => "localhost",
:database => 'test.db'
)
class User < ActiveRecord::Base
#attr_accessible :email, :full_name
attr_accessor :email
attr_accessor :full_name
validates :email, presence: true, uniqueness: true
def initialize(email, full_name)
@email = email
@full_name = full_name
end
end
puts "full_name for user:"
full_name = gets.chomp
puts "email address:"
email = gets.chomp
user = User.new(email, full_name)
#user.save
user = User.create!(email: '', full_name: '')
第一种情况下的例外情况(使用User.create!):
main.rb:42:in `initialize': wrong number of arguments (1 for 2) (ArgumentError)
from /var/lib/gems/1.9.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
from /var/lib/gems/1.9.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
from /var/lib/gems/1.9.1/gems/activerecord-4.2.4/lib/active_record/persistence.rb:50:in `create!'
from main.rb:55:in `<main>'
答案 0 :(得分:2)
抱怨new
方法。根据文档:(http://api.rubyonrails.org/classes/ActiveRecord/Base.html),您不需要initialize
,因为当您从ActiveRecord::Base
继承时,您需要使用哈希初始化您的对象。
user = User.new({email: email, full_name: full_name})
# or
user = User.new(email: email, full_name: full_name)
# then
user.save
您需要从代码中删除initialize
和attr_accessor
。
答案 1 :(得分:1)
尝试评论User#initialize方法并创建这样的新用户:
User.create! email: 'halk@mail.com', full_name: 'Halk'
<强>解释强>
当您根据ActiveRecord::Base
课程的遗产声明AR模型时,您不需要定义自己的#initialize
方法。但你做了。当您调用User::create!
方法时,只传递一个参数 - Hash
两对(使用email和full_name键)。但User#initialize
分别定义两个参数 - email和full_name。所以Ruby异常提出并谈论它:
wrong number of arguments (1 for 2) (ArgumentError)