【问题标题】:Rails NoMethodError when raking耙时Rails NoMethodError
【发布时间】:2015-07-14 02:38:28
【问题描述】:

我今天创建了一个新的 Rails 4 应用程序。我做过很多次的事情。创建了一个基本的用户模型。

    class User < ActiveRecord::Base
        before_save { self.email = email.downcase }
        VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
        validates :name, presence: true, length: { maximum: 50 }
        validates :email, presence: true, length: { maximum: 100 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
        add_index :users, :email, unique: true 
        has_secure_password
        validates :password, length: { minimum: 6 }
    end

我使用 rake db:migrate 运行此迁移:

    class AddIndexToUsersEmail < ActiveRecord::Migration
      def change
        add_index :users, :email, unique: true
      end
     end

我的 schema.rb 显示迁移成功:

    ActiveRecord::Schema.define(version: 20150714015826) do

      create_table "users", force: :cascade do |t|
      t.string   "name"
      t.string   "email"
      t.datetime "created_at",      null: false
      t.datetime "updated_at",      null: false
      t.string   "password_digest"

   end

      add_index "users", ["email"], name: "index_users_on_email", unique: true

   end

但是当我尝试在 Rails 控制台中验证以测试用户模型时,我得到了一个NoMethodError: undefined method add_index。我试过回滚并重新运行迁移,但没有任何变化。该方法在我的class User &lt; ActiveRecord::Base 中正确定义,并迁移到数据库中。

我想知道是否因为我使用 sqlite3 进行开发和使用 pg 进行部署(heroku)在这方面可能会出现问题,但我在这方面的经验不足,无法更好地了解。如果有帮助,我可以提供我的 gemfile。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql ruby-on-rails-4 sqlite


    【解决方案1】:

    您不应该在模型中使用add_index。那里没有地方,完全删除该行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      相关资源
      最近更新 更多