2012-12-30 112 views
2

我从ruby.railstutorial.org学习RoR,我创建了一个模型,当我试图向它添加数据并通过导轨控制台保存时,我得到错误。 (IM用mysql)NoMethodError:undefined方法`保存'轨道控制台

Rails的控制台

User.new(username: "test", password: "test123", password_confirmation: "test123", email: "[email protected]", role: "admin") 
=> #<User id: nil, username: "test", password: "test123", email: "[email protected]", role: "admin", created_at: "2012-01-01 00:00:00", updated_at: "2012-01-01 00:00:00", password_confirmation: "test123"> 

User.save,给出以下错误

NoMethodError: undefined method `save' for #<Class:0x0000000422b628> from /home/ramadas/.rvm/gems/[email protected]/gems/activerecord-3.2.9/lib/active_record/dynamic_matchers.rb:50:in `method_missing' 
from (irb):15 
from /home/ramadas/.rvm/gems/[email protected]/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start' 
from /home/ramadas/.rvm/gems/[email protected]/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start' 
from /home/ramadas/.rvm/gems/[email protected]/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>' 
from script/rails:6:in `require' 
from script/rails:6:in `<main>' 

我的模型

class User < ActiveRecord::Base 
    attr_accessible :email, :password, :password_confirmation, :role, :username 
    validates :username, presence: true , length: { maximum: 50 } 
    VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX } , uniqueness: { case_sensitive: false } 
    before_save { |user| user.email = email.downcase } 
    before_save { |user| user.username = username.downcase } 
    validates :password, presence: true, length: { minimum: 4 } 
    validates :password_confirmation, presence: true 
end 

我已经检查每一个可能的错误可能发生,但没有找到解决办法。请帮我解决并解决这个问题。

回答

11

你打电话给User.saveUser.new(username:...).save

该类/模型User没有在其上定义的save方法,但该类的实例(来自ActiveRecord::Base)。

尝试以下操作:

user = User.new(username:...) 
user.save