首页 > 解决方案 > 被引用用户的属性全部为零

问题描述

我有一个可以接受评论的帖子,这些评论属于用户和帖子。我可以成功创建评论,它将与帖子和用户相关联(通过进入控制台检查,user_id 和 post_id 是否存在),但是当我尝试调用用户的属性(例如 user.username)时不起作用。如果我调用帖子的属性(例如 post.body),它会起作用。在制作评论模型时,我引用了用户并在我的迁移中发布。在我的 user.rb 中,我也尝试过使用has_many :comments, through: :posts,但没有奏效。

用户.rb

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :comments, dependent: :destroy
end

评论.rb

class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :user
end

post.rb

class Post < ApplicationRecord
    belongs_to :user
    has_many :comments, dependent: :destroy            
end

评论控制器.rb

class CommentsController < ApplicationController
    before_action :findpost

    def create
        @comment = @post.comments.build(comment_params)
        @comment.user_id = current_user.id
        if @comment.save
            redirect_to post_path(@post)
        else
            flash[:alert] = "Check the comment form"
        end
    end

    def comment_params
        params.require(:comment).permit(:body)
    end

    private

    def findpost
        @post = Post.find(params[:post_id]) 
    end
end

迁移

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.string :body
      t.references :user, null: false, foreign_key: true
      t.references :post, null: false, foreign_key: true      
      t.timestamps
    end
  end
end

我得到的具体错误

undefined method `username' for nil:NilClass

在哪里comment.user.username被调用

<%= render partial: 'comments/form' %>
<% if @post.comments.count > 0 %>
  <%= @post.comments.each do |comment| %>
    <div>
      <%= link_to author_path(id: comment.user.username) do %>
      <%= comment.user.username %>
      <p><%= comment.body %></p>
    </div>
  <% end %> 
<% end %>

此错误位于comment.user.username. 主要问题是我调用comment.user它的任何属性总是返回 nil(甚至像 id 之类的东西)。

标签: ruby-on-rails

解决方案


推荐阅读