【问题标题】:unable to display validation error from a partial form无法从部分表单显示验证错误
【发布时间】:2012-02-28 09:08:33
【问题描述】:

我无法显示验证错误,即使它正在验证表单。 以我的部分形式

  • 如果@post.errors.any?

似乎是问题所在,@post 为错误返回 false,因此不显示错误。 但是@comment 会为错误返回 true,但我无法用 @comment 替换 @post,因为它会引发未定义的“评论”错误。

我在节目中开始调用的部分形式:

%html
%head
%title= @post.title
  %body
    %h2 Create Comments:
    = form_for([@post, @post.comments.build]) do |f|
      - if @post.errors.any?                # <--- Unsure what to do here..
        #error_explanation
        %h2
          = pluralize(@post.errors.count, "error")
          prohibited this cart from being saved:
        %ul
          - @post.errors.full_messages.each do |msg|
            %li= msg
    = f.label :Name
    %br
    = f.text_field :name 
    %br
    %br
    = f.label :Text
    %br
    = f.text_area :text
   %br
   %br
   = f.submit 

我的 cmets 控制器:

def create
@post = Post.find(params[:post_id])

@comment = @post.comments.build(params[:comment])
   respond_to do |format| 
if @comment.save
    format.html { redirect_to @post }
else
    format.html { redirect_to @post }
end
   end
 end

这是我渲染文件的显示页面:

%html
%head
  %title= @post.title
%body
  %strong Author name:
  = @post.author_name
  %br
  %br
  %strong Title:
  = @post.title
  %br
  %br
  %strong Email:
  = @post.email
  %br
  %br
  %strong Description:
  = @post.description

  %h2 Comments for this Post:

  = render :partial => @post.comments

  = render :partial => "comments/form"

【问题讨论】:

    标签: ruby-on-rails forms validation haml


    【解决方案1】:

    您可以在发布模型上使用validates_associated 来检查关联模型上的验证错误。

    【讨论】:

    • 感谢回复..验证工作正常,但我无法在 if 条件内显示错误 @post 未能满足 if 条件并出来..
    • 如果你使用 validates_associated,@post.errors 会为 cmets 返回错误,你可以很容易的显示出来......
    • 我确实尝试过,但它仍然没有给我错误消息..当我调试代码时,@post 中没有错误消息..
    【解决方案2】:

    如果@comment.save 失败,您必须呈现新的操作

    if @comment.save
        format.html { redirect_to @post }
    else
        render :action => "new" 
    end
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      相关资源
      最近更新 更多