I am trying to pass an array in the URL, which is working fine, but I'd like to know how I can then insert or remove certain values?
For example, I have a link that looks like:
http://localhost:3000/pins?genre_ids[]=1,2,3
I would like to build a set of links that can insert or remove numbers from this URL array.
At the moment, each link I have simply changes the genre_ids[] value completely, where as I'd like to add to it, or take away as needed. This is my code to build the link...
<%= link_to genre[0].title, pins_path( params.merge({ :genre_ids => [genre[0].id] }) ) %>
I think what I'm after is something like params.merge()
but for the value of params[:genre_ids]
I hope you can understand what I mean? If the current URL reads /pins?genre_ids[]=1,2,3
I'd like it so that each link I build includes this current link, with the addition of another number into this array, so that it would look like /pins?genre_ids[]=1,2,3,4
Any help would be greatly appreciated. I'm from a CF background, so I'm still trying to get my head around Ruby and Rails. I am using Rails 4 with Ruby 2.
Thanks, Michael.
You are overwriting your genre_ids
array. You need to combine the two arrays, which you can do using the +
operator:
params[:genre_ids] + [genre[0].id]
I think this will do the trick:
<%= link_to genre[0].title, pins_path( params.merge({ :genre_ids => (params[:genre_ids] + [genre[0].id]) }) ) %>
However, it should be noted that you can end up with duplicate array object values. You may want to consider using the "union" operator |
.
Example:
first = [1,2,3,4]
second = [3,4,5,6]
first + second #=> [1, 2, 3, 4, 3, 4, 5, 6]
first | second #=> [1, 2, 3, 4, 5, 6]
So maybe your link should be:
<%= link_to genre[0].title, pins_path( params.merge({ :genre_ids => (params[:genre_ids] | [genre[0].id]) }) ) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With