由于属性更改而创建相关对象时的NameError

时间:2012-06-12 21:28:37

标签: activerecord camping

这就是我想要发生的事情:我的物品有很多动作。当项目的状态更改时,创建一个新的操作。稍后,我会询问一个Item的相关动作。不幸的是,当我尝试通过状态更改创建操作时,我收到以下异常: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

1 个答案:

答案 0 :(得分:0)

在提交更好的答案以解释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菜鸟。