代码之家  ›  专栏  ›  技术社区  ›  Hemanth

用户,注释关联不工作,comment.user.email没有返回方法错误?

  •  2
  • Hemanth  · 技术社区  · 15 年前

    我有下面给出的具有关联性的模型:

    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
    



    1 回复  |  直到 15 年前
        1
  •  3
  •   morgan freeman    15 年前

    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
    
    推荐文章