添加了两个" belongs_to"到评论模型但无法获得其中一个关联

时间:2013-01-31 05:41:33

标签: ruby-on-rails-3

我目前正在Rails上构建非常简单的评论系统。主要模型是User,Albumpost和Comment。用户可以发布Albumposts。对于每个Albumpost,用户可以向Albumpost添加评论。因此,Comment属于User并属于Albumpost。

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

@comment.user.name

当我尝试在albumpost“show”页面中呈现评论时(/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和评论控制器的相关部分:

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

1 个答案:

答案 0 :(得分:0)

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

 @comment.user = current_user

而不是

 @comment.user_id = current_user.id

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