Passing Error Messages Through Flash

Passing error messages through flash

Firstly,
you can achieve what you're trying to do by setting a single sentence.

flash[:error] = @item.errors.full_messages.to_sentence

I think you could also set it as the array without overflowing the cookie.

flash[:error] = @item.errors.full_messages

But as the other guys say, flash is generally better off being used to return specific messages.

eg.

flash[:error] = "We were unable to destroy the Item"

A common pattern is as such.

def some_action
if @record.action
flash[:notice] = "Action performed successfully"
redirect_to @record
else
flash[:error] = "Action failed"
render :action => "some_action"
end
end

Namely, we have two paths.

  1. Action succeeds. We redirect.
  2. Action fails. We show a page, flash an error, and have @record.errors on hand to call error_messages_for(@record) if we so wish.

Rails: Iterating over array of strings inside hash (flash error messages)

Instead of what you have, you need:

<% flash.each do |name, message| %>
<div class="alert alert-<%= name %>">

<% if Array === message %>
<ul>
<% message.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% else %>
<%= message %>
<% end %>

</div>
<% end %>

If you want to clean this up a bit, you could set all your flash messages to be arrays and eliminate the conditional that way. Then you'd have:

<% flash.each do |name, messages| %>
<div class="alert alert-<%= name %>">

<ul>
<% messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>

</div>
<% end %>

In this case, you'll end up with list items for even single messages, but you can use CSS to format them how you want them.

Cakephp3 pass (custom) validation to flash message

I am using the following method if there are errors:

Controller:

$errors = $action->errors();
$errorMessages = [];

array_walk_recursive($errors, function($a) use (&$errorMessages) { $errorMessages[] = $a; });

$this->Flash->error(__('Your action cannot be saved!'), ['params' => ['errors' => $errorMessages]]);

Template/Element/Flash/error.tcp:

<?php if (isset($params) AND isset($params['errors'])) : ?>
<ul class="collection with-header">
<li class="collection-header"><h5><?= __('The following errors occurred:') ?></h5></li>
<?php foreach ($params['errors'] as $error) : ?>
<li class="collection-item"><i class="material-icons">error</i><?= h($error) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

Result:

result

Just for anyone interested, I am using MaterializeCSS.

Flash error message appearing once after leaving the page the error came from (Rails)

This is happening because flash is cleared between requests.

Your create method leads to a different number of requests depending on if the signup succeeds or not. If it does, the redirect_to creates a new request, which displays and then clears flash. This is the desired behavior.

When the signup fails, you are setting flash and then rendering a view, which doesn't create a new request like redirecting does. This means that your flash message is displayed in the current request and not cleared until after the following request. That's why it seems to be lasting one extra page view.

This exactly the situation for which flash.now was designed. From the docs:

Sets a flash that will not be available to the next action, only to the current.

flash.now[:message] = "Hello current action"

This method enables you to use the flash as a central messaging system in your app. When you need to pass an object to the next action, you use the standard flash assign ([]=). When you need to pass an object to the current action, you use now, and your object will vanish when the current action is done.

Entries set via now are accessed the same way as standard entries: flash['my-key'].

Flash is not displayed in the same view in Rails

In Rails 7 turbo expects POST / PUT / PATCH form submissions to redirect, usually that's create and update controller actions.

To render a template, the response has to have an invalid status, like :unprocessable_entity, otherwise turbo shows an error in the browser console:

turbo.es2017-esm.js:2115 Error: Form responses must redirect to another location
at k.requestSucceededWithResponse (turbo.es2017-esm.js:679)
at A.receive (turbo.es2017-esm.js:450)
at A.perform (turbo.es2017-esm.js:431)

Rails 7 signup form doesn't show error messages

This is one way to set up an update action:

# GET /:user/admin/setting/edit
#
# renders edit.html.erb
def edit
@setting = Setting.find_by(slug: current_user)
end

# PATCH /:user/admin/setting
#
# redirects to user on success
# renders edit.html.erb on failure
def update
@setting = Setting.find_by(slug: current_user)

if @setting.update(settings_params)
# when setting updated

flash[:success] = "Success" # set a message to show on the next request;
# we have to redirect to another url

redirect_to user_url(current_user)
# redirect some place else, like user profile
# this means we're done with `update` action
# and with current request

else # when update/validation failed
# we cannot redirect, because we'll loose our
# invalid object and all validation errors
# NOTE: sometimes if redirect is required
# errors can be assigned to `flash`

flash.now[:danger] = "Oops" # set a message to show in this request;
# we have to render a response
# NOTE: this might be unnecessary, because form
# will also show validation errors

render :edit, status: :unprocessable_entity
# render edit.html.erb template,
# this means we're staying in `update` action
# and in current request
# NOTE: this has nothing to do with `edit`
# action at the top
end
end

You can also use rails generators to get a quick starting code and an example of how everything works.

bin/rails generate scaffold Sample name email
bin/rails db:migrate


Related Topics



Leave a reply



Submit