Question

I have several views where I want to be able to reference a date-based session variable called session[:month_view] which defines what data is pulled from various tables. My trouble is that I want the user to be able to update their views to look at the next month or the previous month and I cannot figure out how to update session[:month_view].

I have a method for setting the session variable if it does not currently exists (effectively setting the :month_view to the current month:

In the controller, called before:

  def set_month_view
    if session[:month_view] == nil
        session[:month_view] = DateTime.new(Time.now.year, Time.now.month, 1, 0, 0, 0, "+00:00")
    end
  end

What I would like is a way of using a link or a form in my views to increment or decrement :month_view by 1 or -1. I am guess that I need to pass an integer to the set_month_view method, but I just don't know how to.

Was it helpful?

Solution

This should do the trick and be quite easy to read/maintain.

Controller methods: (Add redirects or renders as appropriate)

# Make sure this remains in before_filter for the increment and decrement methods too
def set_month_view
  session[:month_view] ||= DateTime.new(Time.now.year, Time.now.month, 1, 0, 0, 0, "+00:00")
end

def increment_month_view 
  session[:month_view] = session[:month_view] + 1.month
end

def decrement_month_view 
  session[:month_view] = session[:month_view] - 1.month
end

View links:

You are viewing month: <%= session[:month_view] %>
<%= link_to 'backwards', decrement_month_view_controller_path %>
<%= link_to 'forwards', increment_month_view_controller_path %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top