2012-12-30 156 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