表单

时间:2017-05-24 21:18:41

标签: ruby-on-rails forms

我的问题是我的错误消息从未打印过,我也不认为验证正在发生。我以前从未做过验证,并且正在努力学习如何做到这一点。

控制器:

def create
    @requests = Request.new(request_params)

    if @requests.save
      redirect_to root_path
      flash[:success] = "Your request has been submitted for approval"
    else
      render 'new'
    end
end

请求模型

class Request < ApplicationRecord

validate :borrow_date_bigger_than_current_date, on: :create

def borrow_date_bigger_than_current_date
    if (:borrow_date.to_s < Date.today.to_s)
        errors.add(:borrow_date, "Checkout date cannot be earlier than the current date") 
    end
end

和一个像这样的表格

form_for @requests do |request|
<% if @requests.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(@requests.errors.count, "error") %> prohibited this message from being saved:</h2>
    <ul>
      <% @requests.errors.full_messages.each do |msg| %>
        <li>
          <%= msg %>
        </li>
      <% end %>
    </ul>
  </div>
  <% end %>
 ... form stuff below here ...
end

1 个答案:

答案 0 :(得分:0)

您确定要执行此操作:

if (:borrow_date.to_s < Date.today.to_s)

您要比较两个Strings,而不是两个Dates