1

私は問題を抱えています、私はこの帰属をコメントモデルにします:

class Comment < ActiveRecord::Base
  attr_accessible :comment
  belongs_to :post
  belongs_to :user

これはユーザーモデルで

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation
  has_many :posts
  has_many :comments

しかし、これは機能しません:

  <% post.comments.each do |comment|   %>
    <div id="comments" >
      <%= comment.user.email %>
           <%= comment.comment %>
    </div>
   <%end%>

エラーが表示されます:

undefined method `email' for nil:NilClass

問題は何ですか、コメントの作成で私は帰属を作成しますので、見てください:

  @comment = @post.comments.create(params[:comment],:user_id => current_user.id)

このエラーを解決する方法を教えてください-

私はこれを試します:

@comment = Comment.new(params[:comment])
@comment.user = current_user
@comment.post = @post
@comment.save
this

@comment = @post.comments.create(params[:comment].merge(:user_id => current_user.id))

この:

@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save

動作しません

同じエラー:

undefined method `email' for nil:NilClass
Extracted source (around line #48):

45: 
46:       <% post.comments.each do |comment|   %>
47:         <div id="comments" >
48:           <%= comment.user.email %>
49:                <%= comment.comment %>
50:         </div>
51:        <%end%>

モデルのコメントに :user_id があるのに何が問題なのかわからない

attr_accessible :comment,:user_id,:post_id

私のフォームメイクはこれです

   <div id="comment_form_<%= post.id %>" style="display: none;" >

      <%= form_for [post,post.comments.build], :remote => true,:class=>"comment" do |com| %>
          <%= com.text_area :comment %>
          <%= com.submit "aaa" %>

      <%end %>

エラーがどこにあるのかわからないので、助けてください。データベースは正しく移行されています

アップデート:

before_filter があり、コメントするページを表示するにはログインする必要があるため、current_user があり、bd をリセットして新しいコメントをログに記録します。メールが機能しません。投稿します。コメント モデルは次のとおりです。

 attr_accessible :comment,:user_id,:post_id
  belongs_to :post
  belongs_to :user
  validates_presence_of :comment ,:on =>:create

モデル ユーザーは次のとおりです。

 class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation,:username
  has_many :posts
  has_many :comments



  attr_accessor :password
  before_save :encrypt_password

  validates_confirmation_of :password
  validates_presence_of :password, :on => :create
  validates_presence_of :email
  validates_uniqueness_of :email
4

3 に答える 3

1

ビューファイル@postの代わりに使用すると役立ちますか?post

于 2013-01-20T12:44:36.043 に答える
0

コメントを保存する時点でcurrent_user がnil でないことを確認する必要があります。また、 post.commentsをリストした時点で、ユーザーのいないコメントはありません。

それだけです。再度動作しない場合は、アクションとモデルの完全なソース コードを見せてください。

于 2013-01-06T02:25:39.507 に答える
0

データベース コメント テーブルに user_id を格納する必要があることを確認してください。@post.comments のいずれかのレコードに user_id が含まれていない場合、エラーがスローされます。user_id 列に 1 つ以上のレコード cantain nil がある場合があります。

使用するselect * from comments where user_id is null;

于 2013-01-08T11:19:22.873 に答える