繁体   English   中英

如何在 Rails 中实现嵌套 model 的存在验证?

[英]How to implement presence validation for nested model in Rails?

完整的源代码在这里https://github.com/tenzan/postfile

创建一个工作正常的帖子。

我有一个父元素“对话”及其子/嵌套元素“帖子”。

在此处输入图像描述

当我在没有输入任何内容的情况下单击“创建帖子”时,它应该会抛出错误“正文不能为空白”。

相反,它给出了另一个错误:

在此处输入图像描述

conversation.rb

class Conversation < ApplicationRecord
  belongs_to :contact
  has_many :posts
end

post.rb

class Post < ApplicationRecord
  belongs_to :conversation
  belongs_to :author, polymorphic: true
  has_rich_text :body

  validates :body, presence: :true
end

posts_controller.rb

class PostsController < ApplicationController
    before_action :authenticate_user!
    before_action :set_conversation

    def create
        @post = @conversation.posts.new(post_params)
        @post.author = current_user
        
       respond_to do |format|
           
           if @post.save
            format.html { redirect_to @conversation }
           end
       end
    end

    private
    def set_conversation
        @conversation = Conversation.find(params[:conversation_id])
    end

    def post_params
        params.require(:post).permit(:body)
    end
end

我显示对话show.html.erb中的所有帖子:

<p id="notice"><%= notice %></p>

<p>
  <strong>Subject:</strong>
  <%= @conversation.subject %>
</p>

<p>
  <strong>Contact:</strong>
  <%= link_to @conversation.contact.name, @conversation.contact %>
</p>

<%= link_to 'Edit', edit_conversation_path(@conversation) %> |
<%= link_to 'Back', conversations_path %>

<div id="posts">
 <%= render @posts %>
</div>

<%= render partial: "posts/form", locals: { conversation: @conversation, post: Post.new } %>

帖子的部分_form.html.erb

<%= form_with model: [conversation, post], id: "form" do |form| %>

<div>
 <% form.object.errors.full_messages.each do |message| %>
  <div><%= message %></div>
  <% end %>
</div>

<br>

 <%= form.rich_text_area :body %>

 <%= form.submit %>

<% end %>

完整的源代码在这里https://github.com/tenzan/postfile

提前致谢。

您的posts_controller中有这个块,这是您的错误出现的地方:

respond_to do |format|           
  if @post.save
    format.html { redirect_to @conversation }
  end
end

respond_to块中,您应该有由format类型标识的块,但是您已经在 Rails 期望format.xxx的块的顶层添加了一条if语句。 if移到您的respond_to块之外,您应该没问题:

if @post.save
  respond_to do |format|           
    format.html { redirect_to @conversation }
  end
else
  DO SOMETHING WITH THE ERROR
end

(另外请注意,如果帖子没有保存,您应该处理错误,即使只是说“对不起,请重试”。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM