我希望在表单中显示错误,并且无法理解为什么此代码不起作用。 的 hotel.rb
class Hotel < ActiveRecord::Base
...
has_many :comments
...
end
comment.rb
class Comment < ActiveRecord::Base
belongs_to :hotel
belongs_to :user
delegate :email, to: :user, prefix: true
validates :body, presence: true, length: { minimum: 5, maximum:200 }
end
酒店/显示。
...
%h2 Comments
#comments
.ui.piled.blue.segment
.ui.header
%i.icon.inverted.circular.blue.comment
Comments
.ui.comments
= render :partial => @hotel.comments
= render 'comments/form', comment: @hotel.comments
...
_form
-if user_signed_in?
= simple_form_for [@hotel, Comment.new] do |f|
=f.error_notification
%br
.ui.reply.form
.field
=f.label :body, "New comment"
=f.input :body, as: :text, label: false
=f.submit 'Add comment', class: "ui fluid blue labeled submit icon button"
-else
=link_to 'Sign in to add comment', new_user_session_path, class: 'ui blue button'
_comment
= div_for comment do
.comment
.content
%span.author= comment.user_email
.metadata
%span.date Posted #{time_ago_in_words(comment.created_at)} ago
.text
= comment.body
如果添加了无法更正._ / p>的too_short和too_long模型
更新
comments_controller
class CommentsController < ApplicationController
def create
@hotel = Hotel.find(params[:hotel_id])
@comment = @hotel.comments.new(comment_params)
@comment.user_id = current_user.id
@comment.save
redirect_to @hotel
end
private
def comment_params
params.require(:comment).permit(:user_id, :body, :hotel_id)
end
end
答案 0 :(得分:2)
我解决了这个问题。
<强> comments_controller 强>
def create
@hotel = Hotel.find(params[:hotel_id])
@comment = @hotel.comments.new(comment_params)
@comment.user_id = current_user.id
@comment.save
respond_to do |format|
if @comment.save
format.html { redirect_to @hotel }
else
format.html { render partial: 'comments/form' }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
<强> _form 强>
-if user_signed_in?
= simple_form_for [@hotel, @comment] do |f|
- if @comment.errors.any?
#error_explanation
%h2
= pluralize(@comment.errors.count, "error")
prohibited this comment from being saved:
%ul
- @comment.errors.full_messages.each do |msg|
%li= msg
%br
.ui.reply.form
=f.error_notification
.inputs
=f.label :body, "New comment"
=f.input :body, as: :text, label: false
.actions
=f.button :submit, 'Add comment', class: "ui fluid blue labeled submit icon button"
-else
=link_to 'Sign in to add comment', new_user_session_path, class: 'ui blue button'
%br
当评论没有保存并写入错误时,此代码会呈现评论表单。
答案 1 :(得分:1)
您的问题出在您的控制器中。在您尝试保存记录之前,错误不会填充。那么在您的实例中,您没有任何流量控制来查看它是否已保存,您只需@comment.save
。如果它不保存或保存,则执行相同的重定向。
试试这个:
if @comment.save
redirect_to @hotel, notice: 'Comment was successfully created.'
else
redirect_to @hotel, notice: 'There was an issue trying to save your comment.'
end
现在使用render :new
,将填充@comment.errors
(假设您尝试了无效长度),现在您应该会看到显示的错误消息!