Rivero Felipe
Rivero Felipe

Reputation: 187

How to manipulate an array inside in activerecord in rails?

I am working in this case. A client can have N quantity of tariffs, I need to save all.

In my ClientController it is working like this:

  def new
    @Client = Client.new()

    4.times do
      tariffs = @Client.tariffs.build
    end
  end

Now from the view "register clients" I received the params like this:

 "client"=>{"name"=>"",
 "gender"=>[""],
 "hair_color_id"=>"",
 "age"=>"",
 "height"=>"",
 "Weight"=>"",
 "orientation"=>"",
 "country_id"=>"",
 "Language"=>[""],
 "service"=>[""],
 "category_id"=>"",
 "description"=>"",
 "tariffs_attributes"=>{"0"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "1"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "2"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "3"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "4"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "5"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "6"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"},
 "7"=>{"quantity"=>"",
 "duration"=>"Hours",
 "price"=>"",
 "currency_id"=>"1"}},
 "homeshow"=>"0",
 "planetariff"=>"0",
 "profileclient"=>"0",
 "city_id"=>"",
 "phonenumber"=>"",
 "fullname"=>"",
 "user"=>{"email"=>"[email protected]",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]"}},
 "commit"=>"Register",
 "locale"=>"en"}

I want to access the array "tariffs_attributes" and save the content there.

I tried with this line inside def create

 @tariffs = Tariff.create(params[:tariffs_attributes])

but I need to update/add the id of the client to each register, like this:

if @client.save

  @tariffs.each do|l|
    @tariff = l
    @tariff.update_attribute(:client_id, @client_id )
    @tariff.save
end

I tried with:

params[:client][tariffs_attributes].each do |l|
       @tariff = Tariff.new(l)
       @tariff.update_attribute(:client_id, @client_id) 
       @tariff.save
end

Any ideas or suggestion?? Thank you in advance

Upvotes: 0

Views: 115

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

You need this:

   params["client"]["tariffs_attributes"].each do |client_id, tariff_attributes|
      @tariff = Tariff.new(tariff_attributes)
      @tariff.update_attribute(:client_id, client_id)
      @tariff.save
    end

Here, you are looping through all the tariffs_attributes which is a hash having key as the client_id and value is the tariff_attributes.

Also, looking at your params hash, all of its keys and values are strings NOT symbols. So, you have to do: params["client"]["tariffs_attributes"] to grab all the tariffs_attributes from the params hash. If you use, symbol :client, like this: params[:client][:tariffs_attributes], it won't work and will get nothing/nil.

Upvotes: 1

Related Questions