Building a calendar navigation in Rails (controller and view links)
- by user532339
Trying to get the next month when clicking the link_to. I've done the following in the view.
<%= form_tag rota_days_path, :method => 'get' do %>
<p>
<%= hidden_field_tag(:next_month, @t1) %>
<%= link_to 'Next Month', rota_days_path(:next_month => @next_month)%>
</p>
<% end %>
class RotaDaysController < ApplicationController
# GET /rota_days
# GET /rota_days.json
# load_and_authorize_resource
respond_to :json, :html
def index
@rota_days = RotaDay.all
@hospitals = Hospital.all
@t1 = Date.today.at_beginning_of_month
@t2 = Date.today.end_of_month
@dates = (@t1..@t2) #Concat variable t1 + t2 together
# @next_month = Date.today + 1.month(params[: ??? ] #Old
if params[:next_month]
# @next_month = Date.today >> 1
@next_month = params[:next_month] + 1.month
@t1 = @next_month.at_beginning_of_month
@t2 = @next_month.end_of_month
@dates = (@t1..@t2)
end
@title = "Rota"
respond_to do |format|
format.html # index.html.erb
format.json { render json: @rota_days }
end
end
I have identified that the reason why this may not be working is in because of the following in my controller @next_month = params[:next_month] + 1.month the last two called methods is defined only on time/date objects. but not on fixnum/string objects. I understand I am missing something from this
Update
I have found that the actual issue is that the `params[:next_month] is a string and I am trying to add a date to to it. Which means I need to convert the string to a date/time object.
Console output:
Started GET "/rota_days" for 127.0.0.1 at 2012-12-14 22:14:36 +0000
Processing by RotaDaysController#index as HTML
User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
RotaDay Load (0.0ms) SELECT `rota_days`.* FROM `rota_days`
Hospital Load (1.0ms) SELECT `hospitals`.* FROM `hospitals`
Rendered rota_days/index.html.erb within layouts/application (23.0ms)
Role Load (0.0ms) SELECT `roles`.* FROM `roles` INNER JOIN `roles_users` ON `roles`.`id` = `roles_users`.`role_id` WHERE `roles_users`.`user_id` = 1 AND `roles`.`name` = 'Administrator' LIMIT 1
Completed 200 OK in 42ms (Views: 39.0ms | ActiveRecord: 1.0ms)