Flash не отображается в том же представлении в Rails

Мне нужно отобразить flash в том же представлении (:edit) после успешного обновления объекта. Если перенаправляю на другое действие - все работает корректно. Но когда мне нужно остаться в :edit - не работает. Может кто-нибудь объяснить мне, в чем моя ошибка... Спасибо!

У меня есть следующий фрагмент кода в моем контроллере:

        def edit
    @setting = Setting.find_by(slug: current_user)
  end

  def update
    @setting = Setting.find_by(slug: current_user)

    if @setting.update(settings_params)
      flash[:success] = I18n.t('admin.settings.edit.success')
    else
      flash[:danger] = I18n.t('admin.settings.edit.not_saved')
    end

    redirect_to edit_admin_setting_url(user: current_user)
  end

routes.rb:

      scope ":user/" do
  namespace :admin do
    resource :setting, only: [:edit, :update]
  end
end

А также edit.html.erb

            <% if flash[:success].present? %>
        <div class="<%= classes + "alert-success" %>">
          <%= icon("fas", "check") %>

          <%= flash[:success] %>

          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      <% end %>

Я также пробовал:

      flash.now[:success] = I18n.t('admin.settings.edit.success')
render :edit

Тоже не работает.

1 ответ

Последний фрагмент кода, который вы показываете

      flash.now[:success] = I18n.t('admin.settings.edit.success')
render :edit

должен работать, если он действительно отображается, я не уверен, где вы его разместили.

В рельсах 7 (или где-либо еще) turboожидает действия обновления/создания для перенаправления. Чтобы отобразить шаблон, ответ должен иметь недопустимый статус, например :unprocessable_entity, иначе выдает ошибку в консоли браузера. /questions/62417538/forma-registratsii-rails-7-ne-pokazyivaet-soobscheniya-ob-oshibkah/62575635#62575635

Вы также должны использовать генераторы рельсов, чтобы получить быстрый стартовый код и пример того, как все работает.

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

Это один из способов настроить действие обновления:

      # 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 settings didn't 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.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
    render :edit, status: :unprocessable_entity
  end
end
Другие вопросы по тегам