如何在Ruby on Rails中显示注释用户名?

时间:2016-03-25 11:21:16

标签: ruby-on-rails ruby

我正在编写一个带有身份验证的简单博客,而且我遇到了一个小问题 - 我需要评论属于当前用户并显示他的名字。这样:

  1. 我使用username:string
  2. 创建了一个用户模型
  3. Post.rb has_many :comments, dependent: :destroy
  4. User.rb has_many :comments
  5. Comment.rb belongs_to :post belongs_to :user
  6. 我正在进行迁移addUserIdToComments user_id:integer
  7. comments_controller.rb 中,我写了@comment.user = current_user
  8. 在我看来,我有<%= comment.user.username %>
  9. 结果我有NameError undefined local variable or method comment for #<#<Class:0xb93859dc>:0xb4b2a2b4> 我已经查看了here,但它没有帮助:(

    comments_controller.rb

    def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(comment_params)
        @comment.user = current_user
        if @comment.save
            redirect_to post_path(@post)
        else
            render 'comments/form'
        end
    end
    
    private
    
    def comment_params
        params.require(:comment).permit(:username, :body)
    end 
    

    show.html.erb

    <div id="post_content">
        <h2><%= @post.title %></h2>
        <p><%= @post.body %></p>
    </div>
    <div id="comments">
        <h2 class="comments">Комментариев: <%= @post.comments.count %></h2>
        <%= render @post.comments %>
        <%= render "comments/form" %>
    </div>
    

    _comment.html.erb

    <div class="comment_content">
        <p><%= comment.user.username %></p>
        <p><%= comment.body %></p>
        <p><%= time_ago_in_words(comment.created_at) %></p>
    </div>
    

    _form.html.erb

    <div id="comment_form">
        <h3 class="form_title">Оставить комментарий</h3>
        <p><%= comment.user.username %></p>
        <%= form_for ([@post, @post.comments.build]) do |f| %>
            <p>
                <%= f.label :Комментарий %>
                <%= f.text_area :body %>
            </p>
            <p>
                <%= f.submit %>
            </p>
        <% end %>
    </div>
    

1 个答案:

答案 0 :(得分:1)

我不明白什么是<%= render @post.comments %>以及它的视图在哪里,我只看到一个评论的子视图

尝试更改

<%= render @post.comments %>

<% @post.comments.each do |comment| %>
    <div class="comment_content">
        <p><%= comment.user.username %></p>
        <p><%= comment.body %></p>
        <p><%= time_ago_in_words(comment.created_at) %></p>
    </div>
<% end %>

或者检查您使用@post.comments

的子视图