1

我目前正在 Rails 上构建非常简单的评论系统。主要模型是 User、Albumpost 和 Comment。用户可以发布相册帖子。对于每个 Albumpost,用户可以向 Albumpost 添加评论。结果,评论属于用户并且属于专辑帖子。

我遇到的问题是,即使我的模型中有正确的关联(见下文),我也无法得到

@comment.user.name

当我尝试在专辑帖子“显示”页面 (/views/albumposts/show.html.erb) 中呈现评论时。当我转到页面时,我无法获取@comment.user.name(不了解关联)并获取

"undefined method `name' for nil:NilClass"

奇怪的是我能得到

@comment.albumpost.content

我仔细检查了我的模型,并为模型添加了正确的外键。我在控制器中做错了吗?

这是我的模型:

class Comment < ActiveRecord::Base
  attr_accessible :body, :albumpost_id, :user_id
  belongs_to :albumpost
  belongs_to :user
end

class Albumpost < ActiveRecord::Base
  attr_accessible :content
  belongs_to :user
  has_many :comments, dependent: :destroy
end

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  has_many :albumposts, dependent: :destroy
  has_many :comments, dependent: :destroy
end

以下是我的 Albumpost 和 Comments 控制器的相关部分:

class AlbumpostsController < ApplicationController
  def show
    @albumpost = Albumpost.find(params[:id])
    @comments = @albumpost.comments
    @comment = Comment.new
    @comment.albumpost_id = @albumpost.id
    @comment.user_id = current_user.id
  end
end

class CommentsController < ApplicationController
  def create
    albumpost_id = params[:comment].delete(:albumpost_id)
    @comment = Comment.new(params[:comment])
    @comment.albumpost_id = albumpost_id
    @comment.user_id = current_user.id
    @comment.save
    redirect_to albumpost_path(@comment.albumpost)
  end
end
4

1 回答 1

0

我认为您应该更喜欢将对象设置为关系而不是设置它们的 ID。例如,您应该这样做:

 @comment.user = current_user

代替

 @comment.user_id = current_user.id

ActiveRecord 将负责设置相应的*_id字段。我不确定它如何处理相反的情况。(如果我理解正确,它应该自动加载

于 2013-01-31T05:52:26.477 回答