ruby-on-rails - user ,评论关联不起作用,comment.user.email 返回无方法错误?

标签 ruby-on-rails ruby-on-rails-3 associations

我有以下模型,其关联如下:-

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: <p>
2:   <% @post.comments.each do |comment| %>
3:    <b>Comment written by:</b>   <%= comment.user.email %><br />
4:       <%= comment.body %><br />
5:   <% end %>
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

最佳答案

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

你可以这样做:

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

关于ruby-on-rails - user ,评论关联不起作用,comment.user.email 返回无方法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062074/

相关文章:

ruby-on-rails-3 - 如何获取rails 3中所有数据库行的范围?

ruby-on-rails - 输出深度嵌套的 json 关联

java - Windows 7 - 将文件类型与 Jar 程序相关联

mysql - 面向文档的数据库作为主数据库和 RDBMS 数据库作为辅助数据库?

javascript - 如何使用资源管道在 Rails 中将文件结尾 &lt;script&gt; 替换为 JS?

ruby-on-rails - Gitlab 架构 - Rails Postgresql

ruby-on-rails - Linux]设置管理员组的权限

ruby-on-rails - 如何测试密码修改成功?

ruby-on-rails - 使用模型名称中的大写字母覆盖 Rails Controller 路由

ruby-on-rails - ActiveRecord 关联