0

私のアプリでは、このエラーが発生します。

ID=のInventoryItemのID=1のベンダーが見つかりませんでした

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を受信し、適切なベンダー(存在する)を見つけようとしています。ベンダーを見つけて関係を構築するための組み込みのrailsメソッドに任せると、問題が発生します。

ベンダー名の入力は、IDを非表示のIDフィールドに割り当てるオートコンプリートです。

可能な解決策:

  1. コントローラで手動で処理し、IDを取得して関係を構築します
  2. Inventory_item.vendor.nameがinventory_item.vendor_idをオートコンプリートするようにフォームを変更し、IDが指定されている場合は名前を削除します
  3. 私が欠けているものを修正しますか?
4

1 に答える 1

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
于 2012-10-16T04:46:24.597 に答える