How to change 3 errors prohibited this foobar from being saved validation message in Rails?
The error_messages_for
helper that you are using to display the errors accepts a :header_message
option that allows you to change that default header text. As in:
The RubyOnRails API is your friend.
error_messages_for 'model', :header_message => "You have some errors that prevented saving this model"
1 error prohibited this {{model}} from being saved
This is a problem with internationalization in rails. One solution that has worked for some is to downgrade the internationalization gem from 0.5.0 to 0.4.2, like so:
sudo gem uninstall i18n
sudo gem install i18n -v 0.4.2
Of course, if you're using RVM to manage your gems, you don't need sudo
in the commands above. How to get number of fields with validation error on rails
obj.errors.keys
will give you the columns which have errors, you can do obj.errors.keys.count
to get the total number of fields having errors.
Also, it will work for nested attributes because the nested attributes column having error will come as nested_model.nested_model_column_name
Rails 4: remove attribute name from error message in custom validator
Unfortunately currently the format of full_messages
for errors is controlled with a single I18n
key errors.format
, hence any change to it will have a global consequences.
Common option is to attach error to the base rather than to the attribute, as full messages for base errors do not include attribute human name. Personally I don't like this solution for number of reason, main being that if the validation error is caused by a field A, it should be attach to field A. It just makes sense. Period.
There is no good fix for this problem though. Dirty solution is to use monkey patching. Place this code in a new file in your config/initializers folder:
module ActiveModel
class Errors
def full_message(attribute, message)
return message if attribute == :base
attr_name = attribute.to_s.tr('.', '_').humanize
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
klass = @base.class
I18n.t(:"#{klass.i18n_scope}.error_format.#{klass.model_name.i18n_key}.#{attribute}", {
:default => [:"errors.format", "%{attribute} %{message}"],
:attribute => attr_name,
:message => message
})
end
end
end
This preserves the behaviour of full_messages (as per rails 4.0), however it allows you to override the format of full_message for particular model attribute. So you can just add this bit somewhere in your translations:activerecord:
error_format:
post:
copy: "%{message}"
I honestly dislike the fact that there is no clean way to do this, that probably deserves a new gem. show validation error message from rails model
You can add errors to your instance using
self.errors.add(:base, "your message here")
You could put attributes name as symbol instead of :base
or whatever you like.In your case
if self.RJan.nil? && self.RFeb.nil? && self.RMar.nil? && self.R1.nil?
self.errors.add(:base, "your message here")
end
Rails: Why can't I save a new model Instance to the database?
class PagesController
# POST /pages
def create
@page = Page.new(page_params) do |page|
# smelly - should be handled inside the model not by the controller
page.slug = helpers.create_slug_from_title(page.title)
end
if @page.save
redirect_to @page, status: :created
else
render :new, status: :unprocessable_entity
end
end
private
def page_params
params.require(:page)
.permit(:foo, :bar, :title)
end
end
You handle invalid user input in a classic web app by re-rendering the form. begin ... rescue
will not work here as .save
does not raise. save!
does but its use here is questionable as exceptions should be used for exceptional cases - invalid user input is an everyday event.On the form you use the errors object to diplay the validation errors to the user:
<%= form_with(model: @page) do |f| %>
<% # @todo extract this into a partial %>
<% if f.object.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(f.object.errors.count, "error") %> prohibited this page from being saved:</h2>
<ul>
<% f.object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Related Topics
Giving an Example of a Cycle in a Directed Graph
Asynchronously Iterating Over The Response of a Request Using Thin and Sinatra
Git: Forcing Tests Before Pushing to Local or Remote Master
How to Create Thor::Group Generators as Args of My_Command
How to Generate The Form for an Existing Model in Rails
Rvm - Macports Won't Update Through Proxy
Ruby Dynamic Arguments in Dynamically Created Methods
What's The Best Way to Extract Excel Cell Comments Using Perl or Ruby
Regex That Matches Valid Ruby Local Variable Names
Error: Failed to Build Gem Native Extension on Windows
Sidekiq to Execute at Specific Time in Every Timezones
Rails How to Tell If a Sidekiq Worker Is Done with Perform_Async
List Array of Days Between Two Dates
Ruby/Active Record: Custom Sorting Order
I Need to Go from HTML to Markdown, Any Suggestion
Watir Changing Mozilla Firefox Preferences
Broken Rails Routes After Implementing Single Table Inheritance