在我的users_controller.rb中,我有:
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
在views / user / _form.html.erb中,我有:
<% if !flash[:error].empty? %>
<div class="alert alert-error">
<p>There are some errors </p>
</div>
<% end %>
在运行测试时我得到:未定义的方法`空?为零:NilClass 我认为这个视图看不到这个变量,也不确定我该怎么把它传递给它。
答案 0 :(得分:1)
你应该写:
<% if flash[:error].present? %>
答案 1 :(得分:1)
您应该使用类似
的代码为partial定义局部变量 # views/user/new.html.erb
= render "form", user: @user, flash: flash
还有一条建议。用糖
# 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 %>