Rails 尝试将字符串转换为日期时间,但未保存到 db [英] Rails trying to convert a string to a datetime, but it's not saving to db

查看:26
本文介绍了Rails 尝试将字符串转换为日期时间,但未保存到 db的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用文本字段作为用户将生日编辑为日期的地方.举个例子,我正在努力,还没有生日.我要添加的生日是 03/21/1986.

I'm trying to use a textfield as a place for users to edit their birthday as a date. With the example, i'm working on, no birthday exists yet. The birthday that i'm trying to add is 03/21/1986.

这是控制器方法:

# PUT /contacts/1/edit
    # actually updates the users data
    def update_user

        @userProfile = User.find(params[:id])
        @userDetails = @userProfile.user_details

        respond_to do |format|

            if @userProfile.update_attributes(params[:user]) 

                format.html {
                    flash[:success] = "Information updated successfully"
                    redirect_to(edit_profile_path)
                }
            else 

                format.html {
                    flash[:error] = resource.errors.full_messages
                    render :edit
                }
            end
        end
    end

这里是模型方法.您可以看到我在 :birthday 调用验证方法以将其转换为日期.似乎一切正常,但没有任何内容保存到数据库中,我也没有收到任何错误.

and here's the model method. You can see i'm calling a validation method on :birthday to convert it to a date. Everything seems to work, but nothing saves to the database and i get no errors.

# validate the birthday format
  def birthday_is_date
    p 'BIRTHDAY = '
    p birthday_before_type_cast

    new_birthday = DateTime.strptime(birthday_before_type_cast, "%m/%d/%Y").to_date
    p new_birthday

    unless(Chronic.parse(new_birthday).nil?)
        errors.add(:birthday, "is invalid")
    end

    birthday = new_birthday
  end

这是我的模型验证方法中 p 语句的打印输出

Here's the printout from my p statements in my model validation method

"BIRTHDAY = "
"03/21/1986"
1986-03-21 12:00:00 -0600

我也刚刚注意到,如果我选择 10/10/1980 的日期,它工作得很好,如果我选择 21/03/1986,我收到一个无效日期错误.

I've also just noticed that if i do a date of 10/10/1980, it works just fine, and if i do a date of 21/03/1986, i get an invalid date error.

编辑以下是一些可能有帮助的更多信息:

EDIT Here's some more info that may help:

查看:

<%= form_for(@userProfile, :url => {:controller => "contacts", :action => "update_user"}, :html => {:class => "form grid_6 edit_profile_form"}, :method => :put ) do |f| %>
...
<%= f.fields_for :user_details do |d| %>
<%= d.label :birthday, raw("Birthday <small>mm/dd/yyyy</small>") %>                         
<%= d.text_field :birthday %>
...
<% end %>

用户模型

class User < ActiveRecord::Base
 ...

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :login, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company, :user_details_attributes

  validates_presence_of :email

  has_one :user_details, :dependent => :destroy
  accepts_nested_attributes_for :user_details
end

user_details 模型

user_details model

require 'chronic'

class UserDetails < ActiveRecord::Base
  belongs_to :user

  validate :birthday_is_date

  attr_accessible :first_name, :last_name, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company
# validate the birthday format
      def birthday_is_date
        p 'BIRTHDAY = '
        p birthday_before_type_cast

        new_birthday = DateTime.strptime(birthday_before_type_cast, "%m/%d/%Y").to_date
        p new_birthday

        unless(Chronic.parse(new_birthday).nil?)
            errors.add(:birthday, "is invalid")
        end

        birthday = new_birthday
      end
end

推荐答案

我最终使用了一个虚拟属性,现在它似乎可以工作了.

I ended up using a virtual attribute and it seems to be working now.

我将此添加到我的模型中

I added this to my model

attr_accessible :birthday_string

def birthday_string
    @birthday_string || birthday.strftime("%d-%m-%Y")
  end

  def birthday_string=(value)
    @birthday_string = value
    self.birthday = parse_birthday
  end

  private

  def birthday_is_date
    errors.add(:birthday_string, "is invalid") unless parse_birthday
  end

  def parse_birthday
    Chronic.parse(birthday_string)
  end

这篇关于Rails 尝试将字符串转换为日期时间,但未保存到 db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆