【问题标题】:NoMethodError: undefined method `has_many' for ActiveRecord:ModuleNoMethodError:ActiveRecord:Module 的未定义方法“has_many”
【发布时间】:2015-11-18 23:36:30
【问题描述】:

我正在尝试通过控制台将用户添加到表用户:u=User.new 但我总是收到错误undefined method `has_many' for ActiveRecord:Module 和我尝试了很多解决方案,但没有任何帮助,所以我尝试删除 has_many 关系以避免错误我得到同样的错误,但是使用 undefined method 'attr_accessor' 或者我在删除时得到attr_accessor 未定义的方法'before_save'。我还有另外 4 个模型,它们是 message-post-friendship-comment。

这是我的用户模型

 class User < ActiveRecord::


  has_many :posts
  has_many :comments
  has_many :messages
  has_many :friendships
  has_many :friends , through=> :friendships
  attr_accessor :email, :password
  before_save :encrypt_password
  after_save :clear_password
  validates_prescence_of :first_name
  validates_prescence_of :last_name
  validates :password, presence: true, length: { minimum: 6 }
  validates_prescence_of :email
  validates_uniqueness_of :email , uniqueness: { case_sensitive: false }
  validates_prescence_of :gender
  validate :that_born_on_is_not_in_the_future



  def self.authenticate(email, password)
      user = find_by_email(email)
      if ((user && user.password_hash) == (BCrypt::Engine.hash_secret(password, user.salt)))
       user
      else
        nil
      end
  end

  def encrypt_password
      if password.present?
        self.salt = BCrypt::Engine.generate_salt
        self.hash = BCrypt::Engine.hash_secret(password, salt)
      end
  end

  def clear_password
    self.password = nil
  end


  def that_born_on_is_not_in_the_future
      self.errors.add :birth_date, 'is in the future' \
  unless self.birth_date <= Date.today end


  end

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activerecord


    【解决方案1】:

    这可能是导致该错误的原因。

    class User < ActiveRecord::
    

    ActiveRecord 是一个模块,类是Base。应该是

    class User < ActiveRecord::Base
    

    【讨论】:

    • 我完全有信心这是正确的答案。我自己立刻注意到了:)
    • @Swards 我试过了,但它导致了另一个错误,即 NameError: undefined local variable or method `through' for User (调用 'User.connection' 建立连接):Class 当我通过关系删除它时,它导致了另一个错误!
    • 这一行的through需要是符号,否则ruby会把它当作方法has_many :friends , through: :friendships
    猜你喜欢
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2014-07-19
    • 2011-11-04
    • 2016-11-25
    相关资源
    最近更新 更多