Question

I'm trying to update multiple rows in the sites table that are associated with the current_user. I have data stored in my database that is encrypted so I have to decrypt the fields and pre-populate the data in fields in a form_tag for the user to see and update all entries upon submit. With this code, I am getting an error saying "expected Hash (got Array) for param `sites'" I'm not sure how to change the code to get the params hash formatted correctly to update all the rows for current_user. Thanks!

Update_all form

<%= form_tag update_all_url method: 'patch' do %>
    <% @sites.each do |site| %>
      <% @pwhint_de = site.pwhint_sb.decrypt 'password' %> # This is decrypting pwhint
      <% @username_de = site.username_sb.decrypt 'password' %> # This is decrypting username
      <tr>    <%= hidden_field_tag 'sites[]', site.id %>
          <td><%= text_field_tag "sites[#{site.id}][company]", site.company %></td>
          <td><%= text_field_tag "sites[#{site.id}][username_sb]", @username_de %></td>
          <td><%= text_field_tag "sites[#{site.id}][pwhint_sb]", @pwhint_de %></td>
      </tr>
    <% end %>
      <%= button_tag "Save all changes" %>
  <% end %>

controller

def update_all_sites
  params[:sites].each do |id, new_attributes|
    Site.find(id).update_attributes new_attributes
end
Was it helpful?

Solution

I think this would work:

#view
<%= hidden_field_tag "sites[#{site.id}][id]", site.id %>
                            ^^^^^^^^^^  ^^
                           #Add this in your view

#controller
def update_all_sites
  params[:sites].each do |attributes|
    Site.find(attributes.delete(:id)).update_attributes new_attributes
  end
  #etc.

The .delete(:key) method on Hashes will delete (NO WAY!?) the corresponding Key/Value pair and return the value, example in IRB console:

1.9.3p448 > a = {b: 12, c: "bonjour"}
# => {:b=>12, :c=>"bonjour"} 
1.9.3p448 > a.delete :c
# => "bonjour" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top