Fernando Maymone
Fernando Maymone

Reputation: 355

How to get hash values from a multiple check_box in rails?

I have a N to M relationship between some multiples elements at my app. So, I want to delete all those relationships on a form. To do that, Im including a check_box at my form, and want to pass the N.id and the M.id to my controller.

Everything is being passed ok to my controller. But I got an error when trying to retrieve those values.

    <% duplicated.each do |element|%>
      <tr id="row_user_<%=element["product_lot"].id%>">
        <td><%= check_box_tag "product_lots[]", {:bol_id => element["bill_of_lading"].id, :product_lot_id => element["product_lot"].id} %>

And in my controller I got:

selected_product_lots = params[:product_lots]

selected_product_lots.each do |element|
  logger.debug("#{element[:bol_id]}")
end    

If I do a print on my params[:product_lots] I have:

["{:bol_id=>3086, :product_lot_id=>6021}"] 

So, I want to know how can I get the bol_id and the product_id from each element. At the moment, im getting a error when I try to do this:

#{element[:bol_id]}"


no implicit conversion of Symbol into Integer 

Upvotes: 0

Views: 689

Answers (1)

Garrett Motzner
Garrett Motzner

Reputation: 3230

Look at the api of check_box_tag:

check_box_tag(name, value = "1", checked = false, options = {}) 
  • The first argument is the name: what the value is stored under, and this usually shows up in params
  • The second argument is the value, and this gets stringified in order to make the html tag.
  • Third is the beginning checked state
  • Finally is the options

So since you are passing an object to value, rails is calling .to_s on that object in order to create the html tag. That is why you are getting the no implicit conversion of Symbol into Integer error, because you are calling […] on a string, which returns the nth character of the string. It's not the best error message, unfortunately, because it doesn't mention that you are accessing a string, not a hash, and it would be the same error message for an array as well. What you probably want is to serialize the value so that you can unserialize it later:

  • Try calling .to_json on the second argument. This should change your value in params[:product_lots] to ['{"bol_id": 3086, "product_lot_id": 6021}'].
  • Notice that this is still a string, so you need to deserialize it (although there is a chance rails could automatically deserialize this, depending on configuration and filters, etc.).
  • try params[:product_lots].map!{|data| JSON.parse(data, object_class: HashWithIndifferentAccess)}. This should now give you an array of hashes (with indifferent access, so you can use symbol keys). (See also Json::parse)
  • you can now get the values you wish
  • consider moving this into a helper, before action/filter, etc., to be able to use it multiple times, potentially for multiple parameters

Upvotes: 2

Related Questions