Rails渲染嵌套注释使用预先加载

我希望能够允许用户向食谱添加评论。我还希望用户能够对这些评论发表评论。它似乎正在运行,但是可能正在进行的查询太多。我研究并看到了许多密切相关的文章,但似乎没有一个对问题有所帮助。不管我如何进行更改,它都行不通。我可以根据需要对注释进行任意数量的评论,但是一旦某个配方有多个注释,它就会崩溃。就像我可以拥有一个或另一个,但不能同时拥有两个,否则它将崩溃。这是我到目前为止的内容:

comment.rb

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

recipe.rb

class Recipe < ApplicationRecord
  has_many :comments,as: :commentable

recipes/show.html.erb

<div class="">
  <h5>Comments:</h5>
  <div class="comment-form">
    <hr />
    <h3 class="subtitle is-3">Leave a reply</h3>
    <%= render @recipe.comments %>
  </div>
  <%= simple_form_for([@recipe,@recipe.comments.build]) do |f| %>
    <div class="field">
      <div class="control">
        <%= f.input :content,input_html: { class: 'input' },wrapper: false,label_html: { class: 'label' } %>
      </div>
    </div>
    <%= f.button :submit,'Leave a reply',class: "button is-primary" %>
  <% end %>
</div>

_comments.html.erb

<div class="box">
  <article class="media">
    <div class="media-content">
      <div class="content">
        <p>
          <strong><%= comment.content %></strong>
        </p>
      </div>
    </div>
  </article>
</div>
<div>
  <div class="">
    <%= form_for([comment,comment.comments.build]) do |f| %>
      <%= f.hidden_field :recipe_id,value: @recipe.id %>
      <%= f.text_area :content,placeholder: "Add a Reply" %><br/>
      <%= f.submit "Reply"  %>
    <% end %>
  </div>
  <div>
    <%= render comment.comments %>
  </div>
</div>

如果我删除<%= render comment.comments %>可以,但是显然不会显示其他评论的评论。如果我只对一个评论发表1条评论,那么我可以随意评论该评论多次。如果我在配方上仅添加一条注释,它将崩溃。如果我尝试输入,它将起作用并显示每个注释都存在,直到完成每个注释为止,然后崩溃。我知道有很多瑰宝,但是我正在学习,并且真的很想从头开始构建并了解正在发生的事情。提前致谢!

Rails渲染嵌套注释使用预先加载

yxm407949656 回答:Rails渲染嵌套注释使用预先加载

我认为,如果您在Comment模型上建立了自我参照关系,那么它将起作用。您需要添加develop或任何您想调用的名称。如果您有其他模型可以发表评论,则可以保留多态所有者。

parent_id

然后在您的评论模型中:

# Migration
def change
  add_column :comments,:parent_id,:integer,foreign_key: true
  add_index :comments,:parent_id
end

如果您使用的是Rails 5,则需要将class Comment < ApplicationRecord belongs_to :commentable,polymorphic: true belongs_to :parent,class_name: 'Comment',inverse_of: :replies has_many :replies,foreign_key: :parent_id,inverse_of: :parent end 添加到optional: true关系中。

本文链接:https://www.f2er.com/3156729.html

大家都在问