使用Rails保存之前将字符串转换为日期

编程入门 行业动态 更新时间:2024-10-27 08:25:07
本文介绍了使用Rails保存之前将字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Very new to Ruby and I've been stuck for hours. Searching everywhere and can't find an answer.

所以我正在使用bootstrap datepicker作为rails gem.

So I'm using the bootstrap datepicker for rails gem.

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

Because I've changed the date format of the datepicker, it won't store in the DB. Guessing this is because the simple_form input is being used as a string to avoid the default date selection inputs applied by simple_form.

我的问题是:如何将字符串"06/18/2013"​​修改/转换为保存到数据库之前的日期?最好由控制器来处理吗?

我的控制器:

# 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 localhost:3000/events/1 Completed 302 Found in 4ms (ActiveRecord: 0.3ms)

推荐答案

您可以在控制器中使用strptime.

You can use strptime in the controller.

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

更多推荐

使用Rails保存之前将字符串转换为日期

本文发布于:2023-10-23 16:03:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521325.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   前将   日期   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!