【发布时间】:2016-03-24 23:46:13
【问题描述】:
我需要知道如何通过javascript显示在rails中创建帖子的验证错误消息
我正在使用 remotipart gem 异步上传图片
后模型是
class Post < ActiveRecord::Base
belongs_to :topic
has_many :comments
has_many :ratings
belongs_to :user
has_and_belongs_to_many :users , join_table: :posts_users_read_status
has_and_belongs_to_many :tags
has_attached_file :image
validates_presence_of :name, :presence => true
validates_attachment_size :image, :less_than => 1.megabytes
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
validates_length_of :name,:maximum => 20
end
验证是名称不应超过 20 个字符
我正在我的索引页面中呈现表单
帖子的索引是
<p id="notice"><%= notice %></p>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: center;
}
</style>
<h1>Listing Posts</h1>
<table style='width:100%' id="posts">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
<th>Topic</th>
<th>Status</th>
<th>No of<br> comments</th>
<th colspan="3">Edit_options</th>
</tr>
</thead>
<tbody>
<%= render @posts%>
</tbody>
</table>
<br>
<%= will_paginate @posts%>
<% if @topic %>
<%= link_to 'New Post', "#" ,id: "posts-link"%> |
<section id ="new-posts">
<%= render 'form'%>
</section>
<%= link_to 'Back to Topics', topic_path(@topic) %>
<% else %>
<%= link_to 'Topics', topics_path %>
<%end%>
创建帖子的javascript是
<%if @posts.save%>
$("#posts").append('<%= j render @posts%>');
alert("Post Created")
$("#post_name").val("")
$("#post_message").val("")
<%else%>
alert(<%=@posts.save!%>)
<%end%>
当我给出超过 20 个字符的名称时,我需要在使用控制台时显示错误消息,我可以通过 .save 来显示它! 但它不适用于 javascript
请任何人帮助我...!
【问题讨论】:
-
alert(<%=@posts.save!%>) -
我也试过了,但是不行
-
试试
<%= j @post.save! %>,你能分享你遇到的错误吗? -
Rich Peck 给出了正确的显示错误的方法。你可以试试..
标签: javascript ruby-on-rails validation activerecord