Rails_learner Rails_learner - 5 months ago 7
Ruby Question

Ruby Retrieving from Array

So i get an array of hashes like this

[1, {"item_name"=>"Estella Top", "item_number"=>"73", "quantity"=>"1", "option_name1_"=>"UK - 4, White"}]

[2, {"item_name"=>"Test Top", "item_number"=>"74", "quantity"=>"1", "option_name1_"=>"UK - 4, Red"}]


I have this create action:

def create
f_turn = extract_items

Page.create!(line_item_id: "#{f_turn.fetch("item_number")}",
option_name: "#{f_turn.fetch("option_name1_")}", quantity: "#{f_turn.fetch("quantity")}")
render nothing: true
end


extract items is a function that extracts the array.

I need those values, but for some reason, its not working.

I've also tried:

def create
f_turn = extract_items

f_turn.each do |key, values|

Page.create!(line_item_id: ["item_number"],
option_name: ["option_name1_"], quantity: "["quantity"])
render nothing: true
end


None of them work. With the latter, instead of the actual value, i get
"[\"item_number\"]"
as the value.
Any help would be appreciated! Thanks in advance!

UPDATE Mistakes in the code

def extract_items
mod_params = Hash.new{|k, v| k[v] = {} }

ITEM_PARAM_PREFIXES.each do |item_data_key|
key_tracker = 1
loop do
current_key = (item_data_key + key_tracker.to_s).to_sym
if params.include? current_key
mod_params[key_tracker][item_data_key] = params[current_key]
else
break
end
key_tracker += 1
end
end
mod_params
end

Answer

If your hash is in the format you posted, this should work:

def create
  f_turn = extract_items

  f_turn.each do |key, values|
    Page.create!(line_item_id: values["item_number"],
      option_name: values["option_name1_"], quantity: values["quantity"])
      render nothing: true
    end
  end
end

You weren't accessing the values from the hash by the looks of your original code.

Comments