views:

103

answers:

2

I have a drop down in one of my views, allowing me to select the number of images on the page. I want to remember the selection on that page, so when the user comes back, the number of images displayed are what they selected last time around.

To achieve this I am setting the cookie value from within the controller like this

if cookies[:per_page].blank?
    cookies[:per_page] = "50" # this is the default value for a new user and incase the existing user deletes the cookie
 else
    cookies[:per_page] = params[:noofimages_perpage].to_s # this is the value selected in the drop down   
 end
     @pp = cookies[:per_page] 
     # further processing with the cookie value here
end

But I don't get the value in cookies[:per_page].

For checking the value in the cookie, I added this line to my view

<%= @pp %>

and the view displays the value only after a refresh.

A Part of the view is here

<select name="noofimages_perpage" onchange="call the controller">
 <option value="50">50</option> 
 <option value="100">100</option>
 <option value="150">150</option>
</select>

After reading a few posts and articles, I understand that cookie write won't be available until the subsequent postback.

Some pointers on how to handle this or a work around please?

As far as possible I want to achieve this without touching the database.

Many Thanks

+1  A: 

A cookie isn't set in the controller but in the response of the controller (because it's a browser thing). that means the cookie is set when the page is rendered. you cant access it on this page but on the next page or refresh.

consider a redirect (to the same page) as a workaround

Labuschin
A: 

Try

per_page = cookies[:per_page]
if per_page.blank?
    per_page = "50" # this is the default value for a new user and incase the existing user deletes the cookie
 else
    per_page = params[:noofimages_perpage].to_s # this is the value selected in the drop down   
 end
 @pp = per_page
 cookies[:per_page] = per_page
 # further processing with the cookie value here
end
Mike Sutton