繁体   English   中英

Rails:显示错误消息[bootstrap-sass,formtastic]

[英]Rails: Showing Error Messages [bootstrap-sass, formtastic]

我正在将Bootstrap-Sass与Formstatic一起使用。 我认为应该使用Formstatic在该字段旁边自动显示错误消息,如下图所示: 这里
(来源: asciicasts.com

但是,即使用户输入了无效的输入,我的应用也不会显示错误消息。 这似乎是一个简单的问题,但我不能落后找出原因。

后控制器

# 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

结束

后模型

  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 %>

更新:在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的方式是错误的。 有人可以帮我解决问题吗?

您通过namecontent状态验证以及content长度验证,这意味着如果您未在namecontent输入任何值,则将出现错误,例如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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM