Errors are displayed twice in rails

こ雲淡風輕ζ 提交于 2019-12-13 17:00:51

问题


I am using carrierwave to upload the profile picture in user model. If the user tries to upload any file that is not an image, then an error must be raised. However the error is displayed twice on the screen. Please help

code for user model class User < ActiveRecord::Base

include CarrierWave::MiniMagick

validates :email, :presence =>true,  :uniqueness => {case_sensitive: false}, :format => { :with=> /([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/, :message => "please enter a valid e-mail" }
validates :name, :presence=>true
validates :password ,:presence =>true, :confirmation=> true #, :length =>{ :minimum=>6, :maximum=>30}, :format=>{:with=>/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}/}

#for the image
mount_uploader :image, ImageUploader

#for the password
has_secure_password

end

**code ImageUploader **

def scale(width, height)
 image.resize widthxheight
   end

   #Create different versions of your uploaded files:
   version :thumb do
     process :resize_to_fit => [50, 50]
   end

  # Add a white list of extensions which are allowed to be uploaded.

   def extension_white_list
     %w(jpg jpeg gif png)
   end

code for error partials

<% if object.errors.any?%>
<ul>
<%= object.errors.full_messages.each do |message|%>
    <li><%= message%></li>
    <%end%>
</ul>

<%end%>

回答1:


In an erb, <% .. %> is used to evaluate the Ruby code within it and <%= .. %> is used to evaluate as well as print the output in erb.

In your below code you have used <%= ... %> twice, once to display the error message with <%= message%> and other to display the same error messages using <%= object.errors.full_messages.each do |message|%> . This is resulting in error messages being displayed twice. Modify your code as below, you just need <%= ... %> while displaying error message not while iterating over the collection of error messages.

<% object.errors.full_messages.each do |message|%> <%# Removed "=" %>
  <li><%= message%></li>
<%end%>



回答2:


Change

<%= object.errors.full_messages.each do |message|%>

to

<% object.errors.full_messages.each do |message|%>

Note the <% at the beginning instead of <%=

<%= is for making the output from the evaluated expression be printed out. Using <% is for indicating that the expression should only be evaluated and output not be printed.



来源:https://stackoverflow.com/questions/29038232/errors-are-displayed-twice-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!