I want to be able to modify on the fly the inventory or quantity of multiple items on an invoice form. Essentially this is for the purpose of affecting stock of certain items which are a part of another item – an example being a gift basket which contains other products.
HOW to do that isn’t my question. For the purpose of explaining where I’m at, here goes:
Tables
1) items
2) item_relationships
item_relationships contain the fields :item_id, :linked_item_id, :item_ratio, :linked_item_ratio, :changes_inventory
Models
# Item.rb
has_many :relationships, :class_name => 'ItemRelationship', :dependent => :destroy
accepts_nested_attributes_for :relationships
# ItemRelationship.rb
belongs_to :item
View
# Relationships can be inserted into the form, so I create one which doesn't have
# an ID so I can use it as a template to copy/insert via javascript. The next block enumerates over existing relationships
<%= render :partial => "item_relationship_form", :locals => {:f => f, :relationship => @item.relationships.new} %>
<% @item.relationships.collect{|rel| rel unless rel.id.nil?}.compact.each do |r| %>
<%= render :partial => "item_relationship_form", :locals => {:f => f, :relationship => r} %>
<% end %>
Partial
<%
disable_hash = relationship.new_record? ? {:disabled => true} : {}
%>
<%= f.fields_for @item.relationships, relationship do |r| %>
<div<%= raw(" style=\"display:none\"") unless disable_hash.empty? %>>
<%= link_to_function "X", "remove_relationship(this)", :style => "font-style:italic", :tabindex => -1 %>
For Every <%= r.select :item_ratio, 1..10, {}, disable_hash %> of this item,
add <%= r.select :linked_item_ratio, 1..10, {}, disable_hash %>
to the <%= r.select :changes_inventory, [["Inventory", true], ["Quantity", false]], {}, disable_hash %>
of <%= r.text_field :linked_item_id, :size => 20, :title => "Use a Product's Barcode Here", disable_hash.key(0) => disable_hash[:disabled] %>
</div>
<% end %>
Now to my problem: The form generates the ids and names of each element as if there were only one relationship. There are no “[]” array brackets anywhere. If I manually set the ID of the relationship before the form is generated, it won’t even generate numbers in the tag attributes that you would normally find.
ex)
item[item_relationship][item_ratio]
instead of
item[item_relationships][][item_ratio]
What gives?
Forget it, I just changed
@item.relationshipsto:relationshipsin thefields_forand it`s working now.