[英]Custom validate doesn't appear to be adding errors
我試圖阻止用戶使用驗證投票給自己。
提交自投票將使基本提示“不接受投票”。 但不會添加驗證錯誤“您無法為自己投票”。
如何將錯誤添加到閃存?
在我的模型中
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 %>
以下
errors.add(:base, "You cannot vote for your self")
將錯誤添加到Model 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.