Rails 3 - 时间存在验证 [英] Rails 3 - Validation for Time existence
问题描述
我有一个带有时间属性的模型.我想检查时间不能为空(更好的选择可能是检查输入是时间,但我不知道如何处理).我试过这个验证:
I have a model with a Time attribute. I want to check that time can not be empty (better choice probably would be to check that input is time but i have no ideas how to deal with that). I tried this validation:
# id :integer not null, primary key
# school_class_id :integer
# meeting_time :time
class Meeting < ActiveRecord::Base
validates :meeting_time,
:presence => { :message => "can't be empty!" }
end
然后我尝试在规范中检查它,但失败了(空闲时间可以,但不应该).我做错了什么?
Then i tried to check this in spec and this fails (empty time is ok but it should not be). What do i do wrong?
# id :integer not null, primary key
# school_class_id :integer
# meeting_time :time
require 'spec_helper'
describe Meeting do
before(:each) do
@class = FactoryGirl.create( :school_class )
@attr_meeting = {
:meeting_theme => 'Text is here',
:meeting_date => "#{Date.today}",
:meeting_time => "#{Time.now}",
:meeting_room => '1234'
}
end
describe "Validations" do
describe "Rejection" do
it "should reject blank time" do
wrong_attr = @attr_meeting.merge( :meeting_time => " " )
@class.meetings.build( wrong_attr ).should_not be_valid
end
end
end
end
错误:
Meeting Validations Rejection should reject blank time
Failure/Error: @class.meetings.build( wrong_attr ).should_not be_valid
expected valid? to return false, got true
推荐答案
在您的示例中,您将 " "
分配给 meeting_time
,而不是 nil代码> 或 <代码>""
.但是 Time
对象不知何故可以从非空的,甚至是空白的字符串中成功生成.将 meeting_time
设置为 ""
或 nil
应该可以解决您的问题.
In your example, you assign " "
to the meeting_time
, not nil
or ""
. But Time
object somehow can be successfuly generated from non-empty, even blank string. Setting meeting_time
to ""
or nil
should solve yout problem.
也许我不完全理解某些东西,但我认为这不是很合乎逻辑和可预测的行为.需要查看来源.
Maybe I don't fully understand something, but I think it's not very logical and predictable behaviour. Need to take a look into the sources.
这篇关于Rails 3 - 时间存在验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!