gpt4 book ai didi

ruby-on-rails - 在使用 Rails 保存之前将字符串转换为日期

转载 作者:数据小太阳 更新时间:2023-10-29 06:48:48 24 4
gpt4 key购买 nike

Ruby 的新手,我已经被困了几个小时。到处搜索,找不到答案。

所以我正在使用 rails gem 的 bootstrap datepicker。

因为我更改了日期选择器的日期格式,所以它不会存储在数据库中。猜测这是因为 simple_form 输入被用作字符串以避免 simple_form 应用的默认日期选择输入。

我的问题是:如何在将“06/18/2013”​​之类的字符串保存到数据库之前将其修改/转换为日期?这最好由 Controller 处理吗?

我的 Controller :

# PUT /events/1
# PUT /events/1.json
def update
@event = Event.find(params[:id])

# Ugghhhh I need help
# @event.event_date = Date.parse(params[:event_date]).to_date

respond_to do |format|
if @event.update_attributes(params[:event])
format.html { redirect_to @event, :notice => 'Event was successfully updated.' }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @event.errors, :status => :unprocessable_entity }
end
end
end

数据库模式:

  create_table "events", :force => true do |t|
t.string "event_name"
t.string "event_location"
t.date "event_date"
t.time "event_time"
t.text "event_content"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "user_id"
t.boolean "approved", :default => true
t.integer "category_id"
end

这是服务器日志:

  Started PUT "/events/1" for 127.0.0.1 at 2013-06-14 02:37:15 -0700
Processing by EventsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RYMdJ0lFmvG0+nVIsTtJXu5fyD/L3/WAKsk9FX6WWgo=", "event"=>{"user_id"=>"1", "category_id"=>"3", "event_name"=>"A Event Name", "event_location"=>"Event Location", "event_date"=>"06/13/2013", "event_time(1i)"=>"2000", "event_time(2i)"=>"1", "event_time(3i)"=>"1", "event_time(4i)"=>"02", "event_time(5i)"=>"18", "event_content"=>"First night"}, "commit"=>"Update Event", "id"=>"1"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Event Load (0.1ms) SELECT "events".* FROM "events" WHERE "events"."id" = ? LIMIT 1 [["id", "1"]]
(0.0ms) begin transaction
(0.0ms) commit transaction
Redirected to http://localhost:3000/events/1
Completed 302 Found in 4ms (ActiveRecord: 0.3ms)

最佳答案

您可以在 Controller 中使用 strptime。

DateTime.strptime("06/18/2013", "%m/%d/%Y")

关于ruby-on-rails - 在使用 Rails 保存之前将字符串转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17105617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com