我有像这样的东西
<div class="userInput">
<%= form_for :scribble do |f| %>
<%= f.text_area :scribble, cols: 65, rows: 4,:maxlength => 255%>
<%= f.submit %>
<% end %>
</div>1)我的Scribble模型有最小和最大字符长度验证,现在如何在这里打印错误消息。如果它是一个实例变量,我知道如何打印,但这是一个符号。
2)此代码存在于application.html.erb中。我不能理解如何将它移动到Scribble控制器的视图中,而不是appliation。问题是这个表单不是独立的,它是控制器涂鸦的动作索引显示的一部分(并且该表单应该始终显示),并且动作索引已经在列出涂鸦。
控制器
def index
@scribbles = Scribble.order("scribbles.scribble DESC").all
end
def show
end
def new
end
def create
@scribble = Scribble.new(profile_params)
@scribble.likes =@scribble.dislikes =@scribble.shares=0;
@scribble.save
@scribbles = Scribble.order("scribbles.scribble DESC").all
render :index
end发布于 2016-07-01 04:19:11
下面是我如何输出任何错误或验证消息:
控制器:
def create
@scribble = Scribble.new(profile_params)
@scribble.likes =@scribble.dislikes =@scribble.shares=0;
if @scribble.save
flash[:notice] = "Scribble is successfully created"
redirect_to root_url
else #
render 'index'
end
end视图:创建一个部分来显示错误消息,例如_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert callout text-center" data-closable>
<p><strong>This form contains <%= pluralize(object.errors.count, 'error') %>.</strong></p>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<button class="close-button" aria-label="Dismiss alert" type="button" data-close>
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<% end %>呈现错误:现在,您可以调用<%= render 'layouts/error_messages', object: @scribble %>并将其放在视图中的任何位置,以呈现错误验证。note: the object is passed, so it can be re-use to any form. credits to Hartl教程。
https://stackoverflow.com/questions/38131250
复制相似问题