【问题标题】:undefined local variable or method <object> for #<Class:0x55ebe50>#<Class:0x55ebe50> 的未定义局部变量或方法 <object>
【发布时间】:2014-12-02 01:25:47
【问题描述】:

我在 Rails 中遇到了多态问题。

我有这些文件:

class CreateExecutions < ActiveRecord::Migration
  def change
    create_table :executions do |t|
      t.integer :player_space_id
      t.integer :what_id
      t.references :what, polymorphic: true 
      t.integer :qty
      t.integer :level
      t.datetime :when_ready

      t.timestamps
    end
  end
end

class Execution < ActiveRecord::Base
    belongs_to :what, :polymorphic => true
end

class Element < ActiveRecord::Base
    belongs_to :game_space
    has_many :levels
    has_many :player_elements
    has_many :executions, :as => what
end

class PlayerSpace < ActiveRecord::Base
    belongs_to :game_space
    belongs_to :user
    has_many :executions, as: :what
end

当我运行具有 Element 的控制器时,出现此错误:

PlayerSpacesController#show 中的名称错误 # 未定义的局部变量或方法“what”

你能帮帮我吗

【问题讨论】:

    标签: ruby-on-rails polymorphism


    【解决方案1】:

    Element 类中有一个小错字: 改变这个:

    class Element < ActiveRecord::Base
      #...
      has_many :executions, :as => what
    end
    

    对此:

    class Element < ActiveRecord::Base
      #...
      has_many :executions, :as => :what
    end
    

    例如,'what' 缺少一个冒号,这意味着它不是一个符号,而是一个变量或方法。由于您没有名为 what 的变量或方法,Ruby 会抛出“未命名的变量或方法”错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2018-04-19
      相关资源
      最近更新 更多