Der*_*ley 6 validation date mongodb ruby-on-rails-3
我有一个Rails 3应用程序(使用Mongodb和Mongoid,如果这有所不同),并且在我的一个模型中,我有一个字段定义为日期类型.
class Participant
include Mongoid::Document
field :birth_date, :type => Date
end
Run Code Online (Sandbox Code Playgroud)
我的控制器正在使用mongo的find_or_initialize_by功能:
class ParticipantController
def create
@participant = Participant.find_or_initialize_by(params[:participant])
if @participant.save
redirect_to participants_path
else
render :new
end
end
end
Run Code Online (Sandbox Code Playgroud)
所有这些归结为:如何使用Mongoid和Rails 3在ActiveModel中进行日期验证?
我想确保在文本框中输入"blah"时不会在分配给.birth_date我的模型字段时引发异常.它应该提供一个很好的验证错误消息,而不使用控制器来进行验证.
这是基本要求:
视图必须是单个文本框.没有其他的.这是我们无法更改的用户要求
验证应该在模型中完成,而不是在控制器或
视图中(javascript或其他)
没有正则表达式格式验证(它们无法正常工作/支持区域设置等)
问题是文本框中的值被分配给.birth_datebefore validates_format_of并运行validates_presence_of.所以...
如何拦截值的赋值,以便在分配之前对其进行验证?是否可以使用ActiveModel在模型中执行此操作?或者这是否要求我在控制器中放置代码来执行此操作?
小智 8
这个小块代码可以解决问题
retVal = "it is a date"
begin
y = Date.parse("rodman was here")
rescue
retVal = "nope not a date"
end
puts retVal
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13266 次 |
| 最近记录: |