Bootstrap-Date选取器日期字段未保存到mysql db

时间:2015-06-26 22:40:08

标签: javascript ruby-on-rails ruby ruby-on-rails-4

我的小表单有日期字段,我正在尝试保存到数据库中。除了datepicker的日期字段外,其他所有字段都被保存.Below是视图和控制器

def addreminder
@user = set_user  

@userremind=UserReminder.new do |u|
  u.user_id=params[:id]
  u.car_id=params[:car]
  u.reminder=Time.local(params[:reminder_date]).strftime('%Y/%d/%m')
  u.service_type=params[:service_type]
  u.active_status=0
end

显示视图

   <%= form_tag("/users/addreminder/#{current_user.id}",:method=>"post",:id => 'add_reminder') do %>
     <%= select_tag(:car, options_for_select(@cars.collect{|u|[u['car_name'],u['id']]}),
       {class: "span3 input-md main_select"}) %>
      <%= label :service_type,"Select Service Type"%> 
      <%= select_tag(:service_type, options_for_select(@services.collect{|u|[u['service_type'],u['service_type']]}),
       {class: "span3 input-md main_select"}) %>     
 <%= (text_field_tag :reminder_date,nil,placeholder: "Select Reminder Date",data: {provide: "datepicker"})%>       
       <%= submit_tag "Remind me",:class=>"btn btn-xlarge"%>
                        <% end %>
       <script>

  $(document).ready(function(){
$('.datepicker').datepicker();
  }); 
 </script>

这是log params

    Parameters:          {"utf8"=>"✓""authenticity_token"=>"7wSEVk24GAgpMtIYoEsa195DYsqB4UsOQ6BoAMzgOfc=", "car"=>"27", "service_type"=>"Oil Change", "reminder_date"=>"07/02/2015", "commit"=>"Remind me", "id"=>"5"}
 User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 5   ORDER BY `users`.`id` ASC LIMIT 1
 User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = ? LIMIT 1  [["id", "5"]]
SQL (0.1ms)  BEGIN
SQL (0.4ms)  INSERT INTO `user_reminders` (`active_status`, `car_id`, `created_at`, `service_type`, `updated_at`, `user_id`) VALUES (?, ?, ?, ?, ?, ?)  [["active_status", 0], ["car_id", 27], ["created_at", Fri, 26 Jun 2015 19:52:10 UTC +00:00], ["service_type", "Oil Change"], ["updated_at", Fri, 26 Jun 2015 19:52:10 UTC +00:00], ["user_id", 5]]
(32.8ms)  COMMIT

数据库架构:

CREATE TABLE user_reminders ( 
  id int(11) NOT NULL AUTO_INCREMENT, user_id int(11) DEFAULT NULL, 
  car_id int(11) DEFAULT NULL, 
  service_type varchar(255) DEFAULT NULL, 
  reminder varchar(25) DEFAULT NULL, 
  active_status int(1) NOT NULL DEFAULT '1', 
  created_at datetime DEFAULT NULL, 
  updated_at datetime DEFAULT NULL, 
  PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8

模特:

class UserReminder < ActiveRecord::Base 
  belongs_to :user 
  attr_accessor :reminder 
  validates :reminder, presence: true 
  # validate :reminder_date_cannot_be_in_the_past 

  def reminder_date_cannot_be_in_the_past 
    errors.add(:reminder, "Can't be in the past") if reminder_date <= Date.today.strftime('%m/%d/%Y') 
  end 
end

1 个答案:

答案 0 :(得分:1)

这有几个问题不起作用:

首先: attr_accessor :reminder行会覆盖Rails已为reminder列提供的setter和getter。因此,您无法在“真实”reminder上设置值。从模型中删除attr_accessor :reminder行。

第二: Time.local无法解析params中的字符串。

Time.local('07/02/2015').strftime('%Y/%d/%m')
#=> "0007/01/01"

改为使用Time.parse

Time.parse('07/02/2015').strftime('%Y/%d/%m')
#=> "2015/07/02"

第三:您的自定义验证器尝试会比较两种不同的东西。 reminder_date不存在,Date.today.strftime('%m/%d/%Y')的格式与文本列中保存的格式不同。将该方法更改为:

def reminder_date_cannot_be_in_the_past 
  if reminder <= Date.today.strftime('%Y/%d/%m')
    errors.add(:reminder, "can't be in the past")  
  end 
end

此外,还有一些事项需要考虑:

IMO将reminder列的类型更改为DATE是有意义的。这样可以使代码更容易,因为您可以比较Date个对象,并且需要strftime方法调用。

在我看来,你似乎没有处理验证错误。可能有意义处理save调用的结果,如果失败则将错误返回给用户。