Jerome
Jerome

Reputation: 6217

Accessing proper array value

The following array ["2", "8", "134", "137", "140"] is generated via user input. The controller action invokes the arrays as follows:

params[:product_ids].each do |product_id|
  @product = Product.where('id = ?', product_id).first
end 

Unfortunately when calling the values in the view (for development control purposes)

<% params[:product_ids].each do |t| %>
  <%= t %> <%= @product.id %><br />
<% end %>

is rendering the proper value for t but is then associating it with 140 five times.

2 140
8 140
134 140
137 140
140 140

thus accessing the LAST item of the array and ignoring the key. When this is attempted in the controller:

params[:product_ids].each do |k, product_id|

it is returning Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

How can the controller be defined to appropriately access the parameter's value?

Upvotes: 1

Views: 111

Answers (3)

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16514

You are assinging the values in a loop to the same variable, put it outside the loop, and use #map to get values as a Transaction model for all product ids, so:

@transactions = params[:product_ids].map do |product_id|
   [ Transaction.where(product_id: product_id).first ]
end

and then:

<%= @transactions %>

Upvotes: 2

Nermin
Nermin

Reputation: 6100

When you use

params[:product_ids].each do |product_id|
  @product = Product.where('id = ?', product_id).first
end 
# you set @product = 2
# @product = 8
# ...
# @product = 140  last value of @product is 140

solution

@products = params[:product_ids].map do |p_id|
   {p_id => Product.find_by(id: p_id)}    
end

In your view

<% @products.each do |k, v| %>
  <%= k %> <%= v %><br />
<% end %>

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51191

In this piece of code:

params[:product_ids].each do |product_id|
  @product = Product.where('id = ?', product_id).first
end

You're updating @product instance variable n times (where n is size of params[:product_ids] table). At the end, @product instance variable holds Product with id which is last element of params[:product_ids], in your case it's 140. I guess it would be better if you set products array, like this:

@products = Product.where(id: params[:product_ids])

so you could iterate over them:

<% @products.each do |product| %>
  <%= product.id %>
<% end %>

Upvotes: 2

Related Questions