Marcin Doliwa
Marcin Doliwa

Reputation: 3659

Flash doesn't work in my partial view

In my users_controller.rb I have:

  def create 
    @user = User.new(params[:user])

    respond_to do |format|
      if @user.save
        redirect_to @user, success: 'User was successfully created.' 
      else
        flash.now[:error] = "There are some user signup errors"
        format.html {render action: "new"} 
      end 
    end 
  end 

In the views/user/_form.html.erb I have:

<% if !flash[:error].empty? %>
  <div class="alert alert-error">
    <p>There are some errors </p>
  </div>
  <% end %>

While running test I get: undefined method `empty?' for nil:NilClass I think that this view cannot see this variable, and not sure how should I pass it there.

Upvotes: 0

Views: 191

Answers (2)

Nick Kugaevsky
Nick Kugaevsky

Reputation: 2945

You should define local variable for partial with code like this

 # views/user/new.html.erb
 = render "form", user: @user, flash: flash

And one more advice. Use sugar

# views/user/_form.html.erb
<% unless flash[:error].empty? %>
   <% flash.each do |key, msg| %>
      <div class="alert alert-<%= key %>">
         <p><%= msg %></p>
     </div>
  <% end %>
<% end %>

Upvotes: 1

Milovan Zogovic
Milovan Zogovic

Reputation: 1580

You should write:

<% if flash[:error].present? %>

Upvotes: 1

Related Questions