I'm creating a registration form for my User model, and I'm trying to put a birthdate in there. I use haml:

= f.date_select :dob, { start_year: 100.years.ago.year, end_year: Date.today.year, prompt: Date.today}

When I refresh the page in the browser I get this message:

undefined method `day' for #<ActiveSupport::HashWithIndifferentAccess:0x00000009db8d88>

What to do? I was looking at this: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select

有帮助吗?

解决方案

The error is coming because of your prompt value. The date helper is looking for a hash of prompt values and you are passing it a Date object which the helper sees as a hash with indifferent access meaning it doesn't have a method like your_prompt_hash.day.

See the example on the Date helper page you linked to:

# Generates a date select with custom prompts.
date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' })

What you're looking for is :default such as:

= f.date_select :dob, { start_year: 100.years.ago.year, end_year: Date.today.year, default: Date.today}

Or you can set this in your controller like:

def new
  @your_model = YourModel.new
  @your_model.dob = Date.today
end

Or you can set the default value for dob in your model like:

class YourModel < ActiveRecord::Base
 after_initialize :set_defaults

 private
   def set_defaults
     self.dob ||= Date.today
   end
end

Either the model or controller solutions would allow you to omit the default value from the date_select call.

其他提示

Try with this

= f.date_select :dob, { start_year: 100.years.ago.year, end_year: Date.today.year}, prompt: {day: Date.today} %>

You can use select_year too in your case

f.select_year(Date.today, :start_year => 100.years.ago.year, :end_year => Date.today.year, :field_name => 'dob')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top