Jerome
Jerome

Reputation: 6217

setting and array of params in rails

A series of objects need to be purchased in a single transaction, however each item must be a different transaction object due to relationship issues.

A confirmation action aims to list each of these items independently. The controller attempts to prepare parameters for viewing each transaction

<% @transactions.each do |transaction| %>
  <%= params[:product_id][:product_id] %>
[...]

as follows:

@transactions = params[:product_ids].map do |product_id|
  @transaction = Transaction.new
  @inventories = Inventory.where(['product_id = ?', product_id]).all
  @my_price = my_price
  params[:product_id][:product_id] = product_id  # sanity check
  params[:product_id][:additional_info] = session[:additional_info]
  params[:product_id][:rate] = @inventories.map(&@my_price).inject(0, :+)
end
@sub_total = @transactions.params[:product_id][:rate].sum

However undefined method []= for nil:NilClass is generated when building the params for each product_id. This command is obviously mistaken. [The approach could also be inefficient/ineffective...]

Upvotes: 0

Views: 97

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

I believe you don't really mean params[:product_id][:product_id], but rather params[product_id][:product_id], since :product_id is a symbol, not a variable.

When setting a new hash in the hash, you need to first define it as such:

params[product_id] = {}
params[product_id][:product_id] = product_id
# ...

This should resolve the undefined method []= for nil:NilClass. I guess you will encounter some more problems (like @inventories.map(&@my_price)) after you fix this one though...


With some guesswork, I guess a code which does what you want will look something like this:

@transactions = params[:product_ids].map do |product_id|
  transaction = Transaction.new
  transaction.product_id = product_id  # sanity check
  transaction.additional_info = session[:additional_info]
  transaction.rate = Inventory.where(['product_id = ?', product_id]).sum(:my_price)
  transaction
end
@sub_total = @transactions.map(&:rate).sum

And the view would be something like this:

<% @transactions.each do |transaction| %>
  <%= transaction.product_id %>
[...]

Upvotes: 1

Related Questions