ruby-on-railsflashrespond-with

Alert flash message not working with respond_with


I'm using responders gem in my Rails 4.2 application. I got a pretty complex situation, where in a Organization model edit view I got a form for a OrganizationUser with one input. Adding user to organization invokes a create action in a OrganizationUsersController. I am using responders there with redirect action, something like this:

def create
  @organization_user = @organization.organization_users.create(organization_user_params)
  respond_with @organization_user do |format|
    format.html { redirect_to edit_organization_path(@organization) }
  end
end

And my translations:

flash:
  actions:
    create:
      notice: '%{resource_name} was successfully created.'
      alert: '%{resource_name} could not be created.'
  organization_users:
    create:
      notice: "Member has been added"
      alert: "Validation error"

The problem is that everything works if a resource is valid and is persisted to database. I am redirected to edit organization view with a proper notice message, but if validation fails I am redirected without any alert.

I can of course set flash alert message unless @organization_user is persisted, but that's the whole point of using responders to set flashes automatically.


Solution

  • Ok I figured it out. It turned out that with validation errors flash was properly set, but it was flash.now instead of flash and after redirect_to flash was deleted. The solution is to use :flash_now => false like so:

    respond_with(@organization_user, :flash_now => false) do |format|
      format.html { redirect_to edit_organization_path(@organization) }
    end