简体   繁体   中英

rails date_select

Right now I am saving my dates as a string in the format of mm/dd/yyyy, but want to convert to date_select but I keep getting errors for some reason.

Here is the code that I am using
the form

 <%= f.date_select :start_date %>

the model

 validates :start_date, :presence => true

but I get an error from my controller saying that it doesnt fit the params.

That's because of the way Rails automatically looks at a database column to figure out what type of object is going to be stored there. In this case, Rails is looking for a Datetime column to be used in conjunction with the date_select helper, but instead it's finding a varchar column.

I would run a migration to drop the start_date column, and re-add it as a datetime column, like so

To generate a new migration:

rails generate migration [name of your migration]

In your case something like:

rails generate migration change_start_date_column_to_timestamp

This will generate a file in your RAILS_ROOT/db/migrations folder, which will look something like:

class ChangeStartDateColumnToTimestamp < ActiveRecord::Migration
  def self.up
  end

  def self.down
  end
end

And you need to modify it to look like:

class ChangeStartDateColumnToTimestamp < ActiveRecord::Migration
  def self.up
    remove_column :table_name, :start_date
    add_column :table_name, :start_date, :timestamp
  end

  def self.down
    remove_column :table_name, :start_date
    add_column :table_name, :start_date, :string
  end
end

Then, when rails pulls the data from the database, it'll automatically convert them to Ruby Time objects.

A word of caution... this will destroy the data in the start_date field. So if you have pre-existing information that needs to be preserved, you need to do something more complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM