簡體   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