ruby-on-rails - 被引用用户的属性全部为零
问题描述
我有一个可以接受评论的帖子,这些评论属于用户和帖子。我可以成功创建评论,它将与帖子和用户相关联(通过进入控制台检查,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 之类的东西)。
解决方案
推荐阅读
- c# - IBMMQDotnetClient 使用 Windows 凭证而不是应用程序指定的凭证
- regex - 我正在寻找一个不允许连续超过星号的正则表达式
- android - Android:尽管有读/写权限,但无法列出文件
- jenkins - pmd 插件在 jenkins 中不可用
- java - 如何在 Java 中替换正则表达式命名捕获组的内容
- c - 忽略:我只是重命名了标题来尝试一下
- python - 为什么通过python中的过滤器时文件听起来很糟糕
- java - 如何存储和检索泛型类型
- spring-boot - org.hibernate.QueryException:在 [] 之前未索引 fromElement
- regex - 如何使用正则表达式替换子字符串中的特定字符?