Weijie Tang
Weijie Tang

Reputation: 83

Rails default parameters on page load

I have a page that I want to display all of the entries in the database for a given week. Each entry in the database has an :entrydate field that contains the date that the entry is for.

In /config/routes.rb:

match "reports/*date" => "reports#index", :defaults => { :date => DateTime.now.strftime('%m/%d/%Y') }

In /app/controllers/reports_controller.rb:

def index
  @reports = Report.where(:entrydate => Date.strptime(params[:date], '%m/%d/%Y').beginning_of_week..Date.strptime(params[:date], '%m/%d/%Y').end_of_week)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render :json => @reports }
    format.js
  end
end

However, when I try to run the page localhost:3000/reports, I get an error:

can't dup NilClass
/app/jruby-1.6.5.1/lib/ruby/1.8/date/format.rb:599:in `_strptime'
/app/jruby-1.6.5.1/lib/ruby/1.8/date.rb:979:in `strptime'
app/controllers/reports_controller.rb:7:in `index'

It works fine if I input a date such as localhost:3000/reports/10/29/2012.

Upvotes: 1

Views: 671

Answers (2)

msergeant
msergeant

Reputation: 4801

It appears as though your default value is not getting set properly. Perhaps this is because it is not a constant?

Anyway, you probably don't want to set the default like this anyway because you have less control over when the default gets set.

I think something like this would be a better approach:

def index
  my_date = params[:date] || DateTime.now.strftime('%m/%d/%Y')
  @reports = Report.where(:entrydate => Date.strptime(my_date, '%m/%d/%Y').beginning_of_week..Date.strptime(my_date, '%m/%d/%Y').end_of_week)

Upvotes: 1

oshikryu
oshikryu

Reputation: 249

It looks like your variable may be getting lost between routes and the controller. Maybe try declaring a default date within the controller itself?

def index
params[:date].blank? ? date = DateTime.now.strftime('%m/%d/%Y') : date = params[:date] 
  @reports = Report.where(:entrydate => Date.strptime(date, '%m/%d/%Y').beginning_of_week..Date.strptime(date, '%m/%d/%Y').end_of_week)

  respond_to do |format|
    format.html # index.html.erb
    format.json { render :json => @reports }
    format.js
  end
end

Upvotes: 0

Related Questions