0

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.

Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62

2 Answers2

1

You should write:

<% if flash[:error].present? %>
Milovan Zogovic
  • 1,541
  • 2
  • 16
  • 24
  • I used unless flash[:error].blank? instead, as based on this question: http://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails it's the thing I was looking for. – Marcin Doliwa Sep 13 '12 at 21:39
1

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 %>
Nick Kugaevsky
  • 2,935
  • 1
  • 18
  • 22
  • It showed up, the problem was empty? as it was generating error when used on nil variable. Thanks for tip. Btw. so every variable I set in controller is available in its templates? or flash is some special variable? – Marcin Doliwa Sep 13 '12 at 21:49
  • Every instance variable defined in view available in view, but not in partial. `flash` is very special. It is available in view also being not instance var in fact. But it also should be passed to partial like every var. – Nick Kugaevsky Sep 13 '12 at 22:49