[英]Errors does not show/ Rails, simple_form
我想显示错误的形式,并且无法理解为什么此代码不起作用。 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
...
_形成
-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'
_评论
= 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
如果添加了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
我解决了这个问题。
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
_形成
-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
当注释不保存时,此代码将呈现注释表单,并写入错误。
您的问题出在您的控制器中。 除非您尝试保存记录,否则不会填充错误。 好吧,在您的实例中,您没有任何流控制来查看它是否已保存,只有@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
(假设您尝试的长度无效),现在您应该看到显示的错误消息!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.