我正在使用Bootstrap-Sass和Formstatic。我认为应该在Formstatic字段旁边自动显示一条错误消息,如下图所示:here http://asciicasts.com/system/photos/227/original/E185I06.png
但即使用户输入的内容无效,我的应用也不会显示错误消息。这似乎是一个简单的问题,但我无法弄清楚背后的原因。
PostController中
# POST /posts
# POST /posts.json
def create
@post = Post.new(params[:post])
@post.view = 0
@post.like = 0
@post.hate = 0
respond_to do |format|
if @post.save
@posts = Post.paginate(:page => params[:page], order: 'like desc', per_page: 10)
format.html { redirect_to posts_path }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
端
PostModel
validates :name, :presence => true
validates :content, :presence => true,
:length => { :minimum => 10, :maximum => 300}
_form(发布)
<% @post = Post.new %>
<%= semantic_form_for @post do |f| %>
<%= f.semantic_errors :name %>
<%= f.inputs do %>
<%= f.input :name, :label => 'name' %>
<%= f.input :content, :label => 'body' %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :button_html => { :class => "btn btn-primary" }, :as => :button %>
<%= f.action :cancel, :as => :link %>
<% end %>
UPDATE:在PostController中,我删除了以下两行
#format.html { render action: "new" }
#format.json { render json: @post.errors, status: :unprocessable_entity }
并添加了
render @post.errors
然后,我得到了
@messages={:name=>["can't be blank"], :content=>["can't be blank", "is too short (minimum is 10 characters)"]}>
所以问题是我渲染json的方式是错误的。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
您通过name
和content
中的状态验证以及内容中的长度验证,这意味着如果您未在name
或content
中输入任何值,那么它会给出像can't be blank
这样的错误,如果content
的值长度小于10且大于300则会出错。
如果要为无效输入传递验证,则必须通过validates_format_of验证。
您在名称或内容中输入了无效的内容? 你能提供输入的无效输入吗?
<强>更新强>
# in /config/initializers/formtastic_config.rb.
Formtastic::SemanticFormBuilder.inline_errors = :sentence
观看视频:http://railscasts.com/episodes/185-formtastic-part-2
获取代码:https://github.com/ryanb/railscasts-episodes/tree/master/episode-185