首页 > 解决方案 > Rails 迁移给出 NoMethodError,我不明白为什么

问题描述

我不知道为什么会这样。我正在尝试对我继承的一些代码进行迁移,但遇到了障碍。这是错误消息,后面是迁移文件代码。

==  AddStorecreditGizmoType: migrating ========================================
rake aborted!
NoMethodError: undefined method `find_by_name' for GizmoCategory(id: integer, description: string):Class
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/base.rb:1876:in `method_missing'
/home/thefonso/site-dev/vendor/plugins/will_paginate/lib/will_paginate/finder.rb:175:in `method_missing_with_paginate'
db/migrate//20090628000954_add_storecredit_gizmo_type.rb:4:in `up'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:282:in `block in migrate'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:282:in `migrate'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:365:in `migrate'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:457:in `run'
/var/lib/gems/1.9.1/gems/activerecord-2.3.14/lib/active_record/migration.rb:409:in `run'
/var/lib/gems/1.9.1/gems/rails-2.3.14/lib/tasks/databases.rake:135:in `block (3 levels) in <top (required)>'
/var/lib/gems/1.9.1/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'
Tasks: TOP => db:migrate:up
(See full trace by running task with --trace)

这是迁移文件代码

class AddStorecreditGizmoType < ActiveRecord::Migration
  def self.up
    # TODO: GizmoCategory.find_by_name("misc") is breaking...why? Attempted to replace with "where" but same error.
    new = GizmoType.new(:name => "store_credit", :description => "Store Credit", :gizmo_category => GizmoCategory.find_by_name("misc"), :required_fee_cents => 0, :suggested_fee_cents => 0)
    new.save!
    DB.execute("UPDATE gizmo_contexts_gizmo_types SET gizmo_type_id = #{new.id} WHERE gizmo_type_id IN (SELECT id FROM gizmo_types WHERE name = 'gift_cert');")
  end

  def self.down
    DB.execute("UPDATE gizmo_contexts_gizmo_types SET gizmo_type_id = (SELECT id FROM gizmo_types WHERE name = 'gift_cert') WHERE gizmo_type_id IN (SELECT id FROM gizmo_types WHERE name = 'store_credit');")
    GizmoType.find_by_name("store_credit").destroy
  end
end

我尝试过使用“where”和“Find_by”,但我一直在为 GizmoCategory 获得相同的“未定义方法 blahblah”

你能为我指出正确的方向吗?我错过了什么?忘记?这里发生了什么事?

哦和版本如下

谢谢

标签: ruby-on-rails

解决方案


activerecord 2.3.14find_by_*中不存在这些方法。改为使用。Model.find

category = GizmoCategory.find(:first, conditions: "name = 'store_credit'")
category.destroy if category

推荐阅读