I am submitting data via ajax to be inserted into the database.
Due to the complex nature of the view and the forms I am sending some redundant information (two forms combined in one).
e.g. the data I'm sending is
partner_id:940
partner_ref: 1
product_1_id:50
product_1_quantity:1
in my controller I then submit everything bar the partner_id
and partner_ref
, to do this I am counting the size of the POST
array, subtracting 2 to account for the 2 parameters I don't want to store and then dividing that by two to get the actual number of products being stored so the result should be 1 but 2 entries are being stored in the table.
# get number of parameters passed and subtract 2 for partner_id and partner_ref
# divide count by two to get actual number of line items
line_items = ((params.size - 2) / 2)
count = 1
for i in count..line_items
item_id = params["product_#{count}_id"]
quantity = params["product_#{count}_quantity"]
# had to add this conditional statement to prevent NULL entries in the database
if !item_id.nil? and !quantity.nil?
line_item = QuoteItem.create(:price_list_item_id => item_id, :quantity => quantity)
end
count = count + 1
end
render :text => line_items # => 2 when it should be 1
It must be something stupid but can't see anything wrong.