2017-07-27 98 views
0

我试图用下面的代码设定日期字段(类型为日期时间):轨验证从功能填写领域

class News < ApplicationRecord 
    after_create :set_date 


    def set_date 
    self.date = created_at.strftime('%Y-%d-%m') 
    end 
end 

db.schema有t.datetime:日期字段 和我从铁轨控制台

News.create(title: 'title3', content: 'contenta abrakadabra3')

新闻被正确地创建检查这一点,但日期字段是零。这是为什么?

新闻ID:4,日期:无,标题:“title3”,内容:“contenta abrakadabra3”,来源:nil,created_at:“2017-07-27 11:49:12”,updated_at:“2017- 07-27 11:49:12“>

回答

0

您正在传递字符串,并且日期字段需要DateTime。

class News < ApplicationRecord 
    before_action :set_date 


    def set_date 
    self.date = created_at 
    end 
end 

如果您想只保存日期。在模型中

class News < ApplicationRecord 
    after_create :set_date 


    def set_date 
    self.date = created_at.to_date 
    end 
end 
+0

'''date'''已经有Datetime类型。我不需要迁移,是的,你是对的我想将日期存储为日期而没有时间。当我在创建完成后在轨道控制台中完成它时,新闻编号:10,日期:“2017-07-27”,标题:“title12”,内容:“contenta abrakadabra12”,来源:无,created_at:“2017-07-27 12:40:36”,updated_at:“ 2017-07-27 12:40:36“ – fernal9301

+0

然后我试着在rails控制台上显示日期,然后再次看到'''nil'''。 – fernal9301

+0

你需要保存后,你设置日期 – dendomenko

0

strftime将你的时间对象转换为字符串创建迁移

class ChangeDateFormatInNews < ActiveRecord::Migration 
    def up 
    change_column :news, :date, :datetime 
    end 

    def down 
    change_column :news, :date, :date 
    end 
end 

然后。我想你想把它作为日期存储。为此,您应该使用to_date

class News < ApplicationRecord 
    after_create :set_date 


    def set_date 
    self.date = created_at.to_date 
    end 
end