簡體   English   中英

rails多態文章評論自動創建一個?

[英]rails polymorphic article comments auto create one?

我正在使用文章和評論測試多態關系

class Article < ApplicationRecord
  has_many :comments, as: :commentable
end
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

我創建了一篇使用foo = Article.create(title: "foo")

問題在這里

我正在使用終端foo.comments.size show 0

但是在瀏覽器中渲染自動創建的注釋?

在此處輸入圖片說明

控制器:

class ArticlesController < ApplicationController
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end
end

您正在視圖中創建實例,因為Comment id: nil表示注釋未持久到數據庫。

也許您認為您正在執行類似@article.comments.build

好的,發現的錯誤是: @article.comments.build

應該是form_for [@article, @article.comments.build]

<h1>show</h1>
<p><%= @article.title %></p>

<section id="comment-form">
    <%= form_for [@article, @article.comments.build] do |f| %>
        body: <%= f.text_field :body %>
        <br>
        <%= f.submit %>
    <% end %>
</section>
comments size: <%= @article.comments.size %>
<ul> <%= render @article.comments %> </ul>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM