I’ve been poking around with this. I’m starting to think this may be a
minor bug in the cookie module… Here’s what I’ve got now:
I’m converting an older app from PHP to Rails. The users makes a few
choices and I display/filter the data to match their choices. I want
to store their choices in a cookie, so they remain “stuck” the next
time the visitor returns to the site.
The problem: Storing a Hash in the cookie with an expiration gives a
“NoMethodError” – not finding “gsub” on the Hash/Array (?).
More specifically:
The user makes a choice as to which book to search in, the source list
comes from the database, and uses abbreviations to track which source
is selected. I converted this almost straight from PHP:
<% @optional_sources.each do |this_source| -%>
<input type=“checkbox” name=“add_sources[]”
value="<%=this_source.abbrev%>" id="<%=this_source.abbrev%>"<%=
‘checked=“checked”’ if
@cookies[‘add_source’].index(this_source.abbrev) %> /> <%=this_source.name%>
<% end -%>
This returns a @params array like this:
@params[‘add_sources’] = [ ‘ABBREV1’, ‘ABBREV2’, ‘ABBREV3’ ]
Of course, this isn’t a very “Railsian” approach. So I implemented the
next set of choices (let’s say, choosing a city) using the check_box
helper:
Cities:
<%
cities = %w{ Toronto Chicago }
cities.each do |this_city|
%>
- <%= check_box ("cities", this_city) %> <%=this_city%>
<% end -%>
Which produces a @params hash like this:
@params[‘cities’][‘Toronto’] = 0
@params[‘cities’][‘Chicago’] = 1
Or, to put it another way, like this:
@params[‘cities’] = { ‘Toronto’ => 0, ‘Chicago’ => 1 }
The problem (at long last):
In the first case (sources), this works fine:
cookies[:sources] = { :value => @params[:add_sources], :expires =>
30.days.from_now }
In the second case (cities), this DOES work:
cookies[:cities] = @params[:cities]
BUT, creates a this-session-only cookie. Trying to set an expiration:
cookies[:sources] = { :value => @params[:cities], :expires =>
30.days.from_now }
… produces the gsub error.