自定义验证似乎没有添加错误

时间:2014-03-21 18:11:37

标签: ruby-on-rails ruby-on-rails-4

我试图阻止用户使用验证进行投票。

提交自我投票呈现基本闪光“投票不被接受”。但不添加验证错误“你不能为自己投票”。

如何将错误添加到闪存中?

在我的模特中我有

class Imagevote < ActiveRecord::Base
    validate :cannot_vote_for_self


    def cannot_vote_for_self
        if voter_id == voted_id
        errors.add(:base, "You cannot vote for your self")
        end
    end
end

在我的控制器中我有

class ImagevotesController < ApplicationController

    def create
        @imagevote = Imagevote.new(imagevote_params)
        @collection = Collection.find(params[:imagevote][:collection_id])
        @imagevote.voted_id = @collection.user_id
        if @imagevote.save
            flash[:success] = "Vote accepted."
            redirect_to @imagevote
        else
            flash[:success] = "Vote not accepted."
            redirect_to :back
        end
    end

    def update
        @imagevote = Imagevote.find(params[:id])
        @collection = Collection.find(params[:imagevote][:collection_id])
        @imagevote.voted_id = @collection.user_id
        if @imagevote.update_attributes(imagevote_params)
            flash[:success] = "Vote changed."
            redirect_to @imagevote
        else
        flash[:success] = "Vote not accepted."
            redirect_to :back
        end
    end

我认为错误是在我的应用程序布局视图中插入的

<% flash.each do |key, value| %>
        <%= content_tag(:div, raw(value), class: "alert alert-#{key}") %>
<% end %> 

1 个答案:

答案 0 :(得分:1)

errors.add(:base, "You cannot vote for your self")

会将错误添加到模型Imagevote的实例中。它们不会添加到flash哈希。

要显示validation error messages,您需要在

中使用以下代码
<% if @imagevote.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@imagevote.errors.count, "error") %>
        prohibited this user from being saved:</h2>
      <ul>
        <% @imagevote.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %> 

在您creating/updating Imagevote对象的视图中。

修改

更新cannot_vote_for_self验证方法,如下所示:

   def cannot_vote_for_self
        if voter_id == voted_id
        errors.add(:vote, "You cannot vote for your self")
        end
    end

在控制器操作中设置flash message如下:

  def create
        @imagevote = Imagevote.new(imagevote_params)
        @collection = Collection.find(params[:imagevote][:collection_id])
        @imagevote.voted_id = @collection.user_id
        if @imagevote.save
            flash[:success] = "Vote accepted."
            redirect_to @imagevote
        else
            flash[:alert] = "Vote not accepted."
            flash[:alert] << @imagevote.errors[:vote].first unless @imagevote.errors[:vote].nil?
            redirect_to :back
        end
    end