[英]Rails 4 - validation doesn't work for a model
我有一個名為RateIndex
的模型:
class RateIndex < ActiveRecord::Base
belongs_to :user
belongs_to :car
validates :name, :presence => true
validates :car_name, :presence => true
validates :description, :presence => true
...
end
控制器為rate_indices_controller.rb
class RateIndicesController < ApplicationController
def new
@rate_index = RateIndex.new
end
...
以及形式:
<%= form_for(@rate_index) do |f| %>
<% if @rate_index.errors.any? %>
<div id="error_explanation">
<h3><%= "#{pluralize(@rate_index.errors.count, "error")} prohibited this game from being saved:" %></h3>
<ul>
<% @rate_index.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
...
但是,當我發送空表格時,沒有顯示驗證錯誤...我也嘗試過更改驗證規則,但即使這樣,它們也將被忽略。
我對它視而不見,已經花了很長時間研究它,但還是一無所獲。
在此感謝您的幫助。
謝謝
編輯:
def create
@rate_index = RateIndex.new(rate_index_params)
respond_to do |format|
if @rate_index.save
format.html { redirect_to '/rate_indices/new', notice: 'Rate was successfully added.' }
format.json { render action: 'show', status: :created, location: @rate_index }
else
format.html { render action: 'new' }
format.json { render json: @rate_index.errors, status: :unprocessable_entity }
end
end
end
您需要致電valid?
首先在您的對象上觸發驗證
@rate_index.valid?
@rate_index.errors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.