【问题标题】:NameError when creating related object due to an attribute change由于属性更改而创建相关对象时出现 NameError
【发布时间】:2012-06-12 21:28:37
【问题描述】:

这就是我想要发生的事情:我的项目有很多操作。当 Item 的状态发生变化时,创建一个新的 Action。稍后,我将询问一个项目的相关操作。不幸的是,当我尝试通过状态更改执行操作时遇到以下异常:NameError at /create; uninitialized constant Shiny::Models::Item::Action

这是我的模型:

module Models
  class Item < Base
    has_many :actions

    def status=(str)
      @status = str
      actions.create do |a|
        a.datetime = Time.now
        a.action = str
      end
    end
  end

  class Actions < Base
    belongs_to :item
  end

  class BasicFields < V 1.0
    def self.up
      create_table Item.table_name do |t|
        t.string :barcode
        t.string :model
        t.string :status
      end

      create_table Actions.table_name do |t|
        t.datetime :datetime
        t.string   :action
      end
    end
  end
end

然后,在控制器中:

class Create
  def get
    i = Item.create
    i.barcode = @input['barcode']
    i.model = @input['model']
    i.status = @input['status']
    i.save

    render :done
  end
end

【问题讨论】:

    标签: activerecord camping


    【解决方案1】:

    在提交更好的答案以解释 Item::Action 的来源之前,这是我修复它的方法:

    module Models
      class Item < Base
        has_many :actions
    
        def status=(str)
          # Instance variables are not propagated to the database.
          #@status = str
          write_attribute :status, str
          self.actions.create do |a|
            a.datetime = Time.now
            a.action = str
          end
        end
      end
    
      # Action should be singular.
      #class Actions < Base
      class Action < Base
        belongs_to :item
      end
    
      class BasicFields < V 1.0
        def self.up
          create_table Item.table_name do |t|
            t.string :barcode
            t.string :model
            t.string :status
          end
    
          create_table Action.table_name do |t|
            # You have to explicitly declare the `*_id` column.
            t.integer  :item_id
            t.datetime :datetime
            t.string   :action
          end
        end
      end
    end
    

    显然我是个 AR 菜鸟。

    【讨论】:

    • 当你有has_many :actions时,ActiveRecord 会尝试查找类 Action。
    猜你喜欢
    • 2022-11-13
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2011-01-23
    • 2020-12-08
    相关资源
    最近更新 更多