0

这就是我想要发生的事情:我的项目有很多动作。当 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
4

1 回答 1

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 菜鸟。

于 2012-06-12T23:02:15.547 回答