ruby - Count size of POST array in Rails -


i submitting data via ajax inserted database.

due complex nature of view , forms sending redundant information (two forms combined in one).

e.g. data i'm sending is

partner_id:940 partner_ref: 1 product_1_id:50 product_1_quantity:1 

in controller submit bar partner_id , partner_ref, counting size of post array, subtracting 2 account 2 parameters don't want store , dividing 2 actual number of products being stored result should 1 2 entries being stored in table.

# number of parameters passed , subtract 2 partner_id , partner_ref # divide count 2 actual number of line items line_items = ((params.size - 2) / 2)  count = 1 in count..line_items     item_id  = params["product_#{count}_id"]   quantity = params["product_#{count}_quantity"]    # had add conditional statement prevent null entries in database   if !item_id.nil? , !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 should 1 

it must stupid can't see wrong.

the parameters rails logs default aren't entire params hash. example, in application if search see following parameters logged default in rails:

parameters: {"utf8"=>"✓", "term"=>"searchterm"} 

but if log result of calling inspect on params hash get:

{"utf8"=>"✓", "term"=>"searchterm", "action"=>"search", "controller"=>"home"} 

this because rails uses params hash store controller , action name in params hash. you've commented, on (post) forms you'll csrf parameters added too.

you better off looking @ how rails can interpret parameters arrays , hashes. mryoshiji commented if use products[][id] rails translate array of hashes. can use explicit array references position.

so text field tags (with values specified illustrate more clearly):

text_field_tag("products[][id]", "1") text_field_tag("products[][quantity]", "11") text_field_tag("products[][id]", "2") text_field_tag("products[][quantity]", "22") 

your params contain products value this:

"products"=>[{"id"=>"1", "quantity"=>"11"}, {"id"=>"2", "quantity"=>"22"}] 

which means don't have calculate anything, can iterate on products , process them:

params["products"].each |product_hash|   product_hash["id"]       # id   product_hash["quantity"] # quantity end 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -