【问题标题】:NoMethodError: undefined method `save' rails consoleNoMethodError:未定义的方法“保存”导轨控制台
【发布时间】:2012-12-30 21:00:11
【问题描述】:

我正在从 ruby​​.railstutorial.org 学习 RoR,我创建了一个模型,当我尝试向其中添加数据并通过 rails 控制台保存时,我遇到了错误。 (我用的是mysql)

Rails 控制台

 User.new(username: "test", password: "test123", password_confirmation: "test123", email: "test@fs.in", role: "admin" )
 => #<User id: nil, username: "test", password: "test123", email: "test@fs.in", 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/ruby-1.9.3-p327@rails3tutorial2ndEd/gems/activerecord-3.2.9/lib/active_record/dynamic_matchers.rb:50:in `method_missing'
from (irb):15
from /home/ramadas/.rvm/gems/ruby-1.9.3-p327@rails3tutorial2ndEd/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
from /home/ramadas/.rvm/gems/ruby-1.9.3-p327@rails3tutorial2ndEd/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
from /home/ramadas/.rvm/gems/ruby-1.9.3-p327@rails3tutorial2ndEd/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+\-.]+@[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

我已经检查了所有可能发生的错误,但没有找到解决方案。请帮我弄清楚并解决这个问题。

【问题讨论】:

    标签: ruby-on-rails railstutorial.org


    【解决方案1】:

    你打电话给User.save还是User.new(username:...).save?

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

    尝试以下方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多