【问题标题】:Different Output Based on Order of my Code (Rails)基于我的代码顺序的不同输出(Rails)
【发布时间】:2015-08-01 02:05:24
【问题描述】:

我正在学习 Rails 教程,并且刚刚将 Comment 模型与我的 Article 模型相关联。

我有一个视图文件,它在此处显示一篇文章及其所有 cmets (app/views/articles/show.html.erb):

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.body %>
</p>

<h2>Comments</h2>
<% @article.comments.each do |comment| %>
    <p>
        <strong>Commenter:</strong>
        <%= comment.commenter %>
    </p>

    <p>
        <strong>Body:</strong>
        <%= comment.body %>
    </p>
<% end %>

<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |comment| %>
    <p>
        <%= comment.label :commenter %>
        <%= comment.text_field :commenter %>
    </p>
    <p>
        <%= comment.label :body %>
        <%= comment.text_area :body %>
    </p>
    <p>
        <%= comment.submit %>
    </p>
<% end %>

这样排列的代码——添加评论表单上方显示的 cmets——在浏览器中一切正常

但是,当我重新排列以使评论表单位于 cmets 部分上方时,如下所示:

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @article.body %>
</p>



<h2>Add a comment:</h2>
<%= form_for([@article, @article.comments.build]) do |comment| %>
    <p>
        <%= comment.label :commenter %>
        <%= comment.text_field :commenter %>
    </p>
    <p>
        <%= comment.label :body %>
        <%= comment.text_area :body %>
    </p>
    <p>
        <%= comment.submit %>
    </p>
<% end %>

<h2>Comments</h2>
<% @article.comments.each do |comment| %>
    <p>
        <strong>Commenter:</strong>
        <%= comment.commenter %>
    </p>

    <p>
        <strong>Body:</strong>
        <%= comment.body %>
    </p>
<% end %> 

我在页面底部留下了一个标记为评论者和正文的 html 元素,但其中没有任何内容。例如,如果我对文章发表过一次评论,它会显示预期的评论,但还会在其下方显示一个额外的空白评论。在最初的代码安排下,没有额外的空白注释,只有我在文章上写的单个预期注释。

为什么像这样重新排列文本会在底部添加一个空白注释?

我的文章控制器显示操作:

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

我的 cmets 控制器创建动作:

def create 
    @article = Article.find(params[:article_id])    
    @comment = @article.comments.create(comment_params)

    redirect_to article_path(@article)
end

【问题讨论】:

    标签: ruby-on-rails controller


    【解决方案1】:

    一旦你这样做(你在表格中这样做),就会发生什么

    @article.comments.build
    

    它会针对 @article 初始化评论,然后当您尝试获取表中以下文章的 cmets 时,也会显示相关评论。你要做的是,用这个更新下表

    <% @article.comments.select(&:persisted?).each do |comment| %>
        <p>
            <strong>Commenter:</strong>
            <%= comment.commenter %>
        </p>
    
        <p>
            <strong>Body:</strong>
            <%= comment.body %>
        </p>
    <% end %> 
    

    主要换行是这样的

    <% @article.comments.select(&:persisted?).each do |comment| %>
    

    这将只为该文章选择数据库中存在的那些 cmets

    【讨论】:

    • 太棒了!这行得通,而且非常直观。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    相关资源
    最近更新 更多