用户评论协会不灵,comment.user.email回报没有方法错误? [英] user , comment association not working, comment.user.email returns No method error?

查看:122
本文介绍了用户评论协会不灵,comment.user.email回报没有方法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关联以下型号下面给出: -

I have the following models with associations as given below:-

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  

但是当我尝试访问的评论的用户详细信息我没有得到任何方法误差:(。结果
在浏览器中显示的错误是如下: -

But when I try to access's comment's user details I GET NO METHOD ERROR :(.
The error displayed in browser is as below:-

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: 

我的模式是如下: -

My schema is as below:-

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  

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

My comments create method is as follows:-

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

As you can see I used devise for user model .
Any idea of what I'm doing wrong?Please help me out !!!
I'm using Rails 3.0.1

推荐答案

我相信,你是不是保存@comment赋予它的USER_ID之后。你做得@ comment.user_id = current_user.id,但这种变化不会反映在数据库中。

I believe that you are not saving the @comment after assigning it's user_id. You're doing @comment.user_id = current_user.id, but this change is not reflected in the database.

您可以这样做:

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

这篇关于用户评论协会不灵,comment.user.email回报没有方法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆