2012-06-12 39 views
0

以下是我想要发生的事情:我的项目有很多操作。当一个项目的状态改变时,创建一个新的操作。稍后,我会询问一个项目的相关操作。不幸的是,当我尝试通过状态更改进行操作时,我收到以下异常:NameError at /create; uninitialized constant Shiny::Models::Item::Action由于属性更改而创建相关对象时的NameError

这里是我的模型:

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 

回答

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 noob。

+0

当你有'has_many:actions'时,ActiveRecord会尝试找到Action类。 –

相关问题