简体   繁体   English

Rails 4-验证不适用于模型

[英]Rails 4 - validation doesn't work for a model

I have a model called RateIndex : 我有一个名为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

The controller is rate_indices_controller.rb 控制器为rate_indices_controller.rb

class RateIndicesController < ApplicationController
  def new
    @rate_index = RateIndex.new
  end
  ...

And the form: 以及形式:

<%= 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 %>
  ...

But when I send the empty form, there are no validation errors displayed... I've tried to also change the validation rules, but even then they are ignored. 但是,当我发送空表格时,没有显示验证错误...我也尝试过更改验证规则,但即使这样,它们也将被忽略。

I am kind of blind from it, looking into it quite a while, but still nothing. 我对它视而不见,已经花了很长时间研究它,但还是一无所获。

I'd be grateful for every help here. 在此感谢您的帮助。

Thank you 谢谢

EDIT: 编辑:

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

you need to call valid? 您需要致电valid? on your object first to trigger the validation 首先在您的对象上触发验证

@rate_index.valid?
@rate_index.errors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM