当前位置: 动力学知识库 > 问答 > 编程问答 >

Rails prints "Can't be blank" instead my custom error message

问题描述:

In User model I wrote:

class User < ActiveRecord::Base

has_secure_password

validates :name, :presence => { allow_blank: false, message: "This field can't be empty" }

end

But it prints "Can't be blank". What is the problem here?

UPDATE

def create

@user = User.new(user_params)

if @user.save

redirect_to "http://bookworm.az:3000"

else

session[:name] = @user.name

session[:username] = @user.username

session[:email] = @user.email

error = @user.errors.to_a.to_sentence(two_words_connector: ',')

delimeter = error.split

error = error.gsub(delimeter[0], '')

show_error = error.split(",")

flash[:notice] = show_error[0]

redirect_to :back

end

View code:

 <% if flash[:notice] %>

<p class="error">

<%= flash[:notice] %>

</p>

<% end %>

Yesterday it works! But today - no! I did not change anything!

网友答案:

You can try this

# config/locales/en.yml

 en:
   activerecord:
     attributes:
       name: "Name"

   errors:
     models:
      user:
        attributes:
          name:
            blank: "This field can't be empty"

In controller

 def create
  @user = User.new(user_params)
  if @user.save!
     redirect_to "http://bookworm.az:3000"
  else


    render :new
  end
end

In View

 <%= form_for @user do |f| %>
  <% if @user.errors.any? %>
   <ul>
     <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
   </ul>
   ....
  <% end %>
网友答案:

Use locales to show customized error messages since it is the most recommended way:

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        name: ""
    errors:
      models:
        user:
          attributes:
            name:
              blank: "This field can't be empty"

Hey, you could see config/locales/en.yml file by default in a Rails application. So, make use of it since you want to customize the error message and it is the suggested way. If it was a direct one, it would have been easy to do it in a Model itself.

Model:

class User < ActiveRecord::Base
    has_secure_password
    validates_presence_of :name
end

Controller:

def create
    @user = User.new(user_params)
    if @user.save
        redirect_to "http://bookworm.az:3000"
    else
        render :new
    end
end

View:

<%= @user.errors.full_messages.first if @user.errors.any? %>

Please try as above. Hope it helps :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: