对于我的应用程序,用户可以通过用户自己的显示页面上的 simple_form 创建帖子。我在需要存在的帖子模型中进行了验证。当没有输入时,我没有收到错误通知,告诉我我的字段为空白,而是 ActiveRecord::RecordInvalid, Validation failed。
我如何让它在表单上创建错误通知来告诉我一个字段是空白的?
请参阅下面的代码。
用户.rb
has_many :posts
post.rb
attr_accessible :user_id, :category
belongs_to :user
validates :category, presence: true
查看/用户/show.html.erb
<%= render 'posts/form' %>
查看/帖子/_form.html.erb
<p>Add Post:</p>
<%= simple_form_for([@user, @user.posts.build]) do |f| %>
<%= f.error_notification %>
<%= f.input :category %>
<%= f.submit "Add Post", :class => "btn btn-header" %>
<% end %>
post_controller.rb
def create
@user = User.find(params[:user_id])
@post = @user.posts.build(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to user_path(@user), notice: 'Post was successful.' }
format.json { head :no_content }
else
format.html { redirect_to user_path(@user) }
format.json { render json: @post.user.errors, status: :unprocessable_entity }
end
end
end