用户,评论关联不起作用,comment.user.email返回No方法错误?

我有以下模型与下面给出的关联: –

class Comment < ActiveRecord::Base belongs_to :post belongs_to :user end class Post < ActiveRecord::Base belongs_to :user has_many :comments end class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me has_many :posts has_many :comments end 

但是,当我尝试访问评论的用户详细信息时,我没有获得方法错误:(。
浏览器中显示的错误如下: –

 undefined method `email' for nil:NilClass 1: 

2: 3: Comment written by:
4:
5: 6:

我的架构如下: –

 create_table "comments", :force => true do |t| t.integer "post_id" t.integer "user_id" t.text "body" .... truncated end create_table "posts", :force => true do |t| t.integer "user_id" t.integer "sell_or_buy" t.string "title" t.text "body" .... truncated end create_table "users", :force => true do |t| t.string "email", :default => "", :null => false t.string "encrypted_password", :limit => 128, :default => "", :null => false .... truncated end 

我的评论创建方法如下: –

 class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment]) @comment.user_id = current_user.id redirect_to post_path(@post) end end 

如您所见,我使用了设计用户模型。
知道我做错了什么吗?请帮帮我!!!
我正在使用Rails 3.0.1

我相信你在分配它的user_id后没有保存@comment。 您正在执行@ comment.user_id = current_user.id,但此更改未反映在数据库中。

你可以这样做:

 def create @post = Post.find(params[:post_id]) @comment = @post.comments.new(params[:comment]) @comment.user_id = current_user.id @comment.save redirect_to post_path(@post) end