vendredi 24 avril 2015

How to set parameters inside a loop from controller in Rails 4?

Hello all I want to set parameters from controller. I have nested params, and there are many of them. I want to iterate through params and set their values.

Here is my request model which has nested model filled_cartrdige:

has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
accepts_nested_attributes_for :filled_cartridges , allow_destroy: true

And here are my params when form is submitted:

filled_cartridges_attributes"=>{"0"=>{"cartridge_name"=>"HP new 2",
 "_destroy"=>"false",
 "client_id"=>"",
 "request_id"=>"",
 "cartridge_id"=>""}}

Notice empty params like client_id, I want to set their values inside controller before saving.

This is how I am trying to do it:

# Iterate through nested params
params[:request][:filled_cartridges_attributes].each do |_,value|
# set param value,
  value[:client_id] = @client.id
Is it allowed to do like that? Also do i need hidden fields for those params that are set from controller.

Aucun commentaire:

Enregistrer un commentaire