在我的应用程序中,我收到此错误。
对于 ID = 的 InventoryItem,找不到 ID = 1 的供应商
库存项目.rb
belongs_to :vendor
accepts_nested_attributes_for :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 并尝试找到正确的供应商(存在),当留给用于查找供应商和建立关系的内置 rails 方法时会出现问题。
供应商名称的输入是一个自动完成,它将 id 分配给隐藏的 id 字段。
可能的解决方案:
- 在控制器中手动处理,获取 id 并建立关系
- 更改表单,以便 inventory_item.vendor.name 自动完成 inventory_item.vendor_id 并在提供 id 的情况下去除名称
- 修复我丢失的东西?