2012-10-16 41 views
0

在我的應用程序中,我收到此錯誤。如何從Rails中的子項創建父項?

與ID = 1爲InventoryItem與ID找不到供應商=

InventoryItem.rb

belongs_to :vendor 
accepts_nested_attributes_for :vendor 

Vendor.rb

has_many :inventory_items 

_form.html。 erb

<%= simple_nested_form_for @inventory_item, :html => {:class => 'form-inline' } do |f| %>                      


    <h2>Inventory Data</h2> 
    <%= f.input :name, :input_html => {:autocomplete => :off, :placeholder => 'Item Name' }%> 
    <%= f.input :id, :as => :hidden %> 

    <%= f.simple_fields_for :vendor do |v| %> 
     <%= v.input :name, :label => 'Vendor name', :input_html => {:autocomplete => :off, :placeholder => 'Vendor Name' } %> 
     <%= v.input :id, :as => :hidden %> 
    <% end %> 
<% end %> 
    ----snip---- 

我的參數哈希算法得出相應

{"utf8"=>"✓", 
"authenticity_token"=>"ZY9fum4XGStTMNbpRQxrzmP7PT3A6BUU+wOymV0fZ/c=", 
"inventory_item"=>{"name"=>"testing", 
"id"=>"7678", 
"vendor_attributes"=>{"name"=>"test", 
"id"=>"1"}, 
"item_instances_attributes"=>{"0"=>{"barcode"=>"", 
"funding_source"=>"", 
"serial"=>"", 
"version"=>"", 
"website_id"=>"", 
"item_type"=>"Retail", 
"type_of_at"=>"Vision", 
"os"=>"Mac", 
"registration_key"=>"", 
"dealer_price"=>"", 
"retail_price"=>"", 
"reuse_price"=>"", 
"estimated_current_purchase_price"=>"", 
"cost_to_consumer_for_loan"=>"", 
"repair_status"=>"Working", 
"date_reviewed"=>"10-15-2012", 
"qr_url"=>"", 
"location"=>"", 
"restrictions"=>"", 
"notes"=>""}}}, 
"commit"=>"Create Inventory item"} 

inventory_items_controller.rb

def create 
    params[:inventory_item].delete(:estimated_dealer_price) 
    @inventory_item = InventoryItem.create(params[:inventory_item]) 
    @inventory_item.name = inventory_item.name.downcase 

    if inventory_item.save 
     redirect_to(inventory_items_path, :notice => "Item created.") 
    else 
     render 'new' 
    end 
    end 

控制器接收ID,並試圖找到合適的供應商(其存在),留下來的時候有問題用於查找供應商並建立關係的內置導軌方法。

供應商名稱的輸入是一個自動完成,它將id分配給隱藏的id字段。

可能的解決方案:手動

  1. 手柄控制器,獲取id和建立關係
  2. 變化形式,這樣,如果一個所述inventory_item.vendor.name自動完成inventory_item.vendor_id和剝離名稱ID提供
  3. 修復我錯過的東西?

回答

0

聽起來像你有相反的意思,通常孩子不應該創建父記錄,你應該檢查它是否可行,以使其成爲更加標準的父母子女關係方式。

這就是說,你可以做這樣的事情

InventoryItem << ActiveRecord::Base 
    belongs_to :vendor 
    def vendor_attributes=(params) 
    self.vendor = Vendor.find(params[:id]) || Vendor.create_by_name!(params[:name]) 
    end 
end 
+0

的形式創建它有1個小孩和小孩有多個孩子的InventoryItem,所以通過建立供應商形式的InventoryItem將笨重。我也很好奇查詢首先失敗的過程,因爲錯誤消息看起來像是試圖對你的代碼補丁做同樣的事情。 – Kosmonaut

相關問題