【问题标题】:Ruby on rails cannot display form for comments before displaying commentsRuby on rails 在显示评论之前无法显示评论表单
【发布时间】:2014-09-09 13:13:55
【问题描述】:

我的帖子上有 cmets,我可以先显示我的 cmets,然后再显示我的 cmets,然后再显示我的 cmets,但不能先显示我的表单,然后再显示 cmets。我很确定原因是 .build:

<%= form_for([@question, @question.replies.build]) do |f| %>

因此,您只需在此表单中输入评论正文并单击提交即可。

显示的数据是:commenter(评论的用户)、评论的body和created_at。

我得到的错误是:

undefined method `first_name' for nil:NilClass

提取的来源是:

          <%= render @question.replies%>
   <% @question.replies.each do |reply| %>
       <div class="reply">
         <p><%= link_to reply.user.first_name, user_profile_path(reply.user) %> says:</p>
         <p><%= reply.body %></p>
         <p>Answered <%= time_ago_in_words(reply.created_at) %> ago</p>
         <% if current_user==reply.user %>

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    您应该有某种可用的@current_user 对吗?

    所以尝试做这样的事情

    <%= form_for([@question, @question.replies.build.tap{|a| a.user = @current_user}]) do |f| %>
    

    问题是您使用 form_for 构建的评论的用户值为零。

    【讨论】:

      【解决方案2】:

      对此的解决方案是,您必须在显示任何内容之前检查回复是否为零。

      <% @question.replies.each do |reply| %>
          <% unless reply.user.nil? %>
      

      【讨论】:

        猜你喜欢
        • 2011-10-02
        • 1970-01-01
        • 2013-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 2019-12-07
        • 1970-01-01
        • 2013-04-08
        相关资源
        最近更新 更多