2012-06-12 35 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類。 –

相關問題