2

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

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

これ

@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 %>

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

4

3 に答える 3

0
# Model
class Comment < ActiveRecord::Base
  attr_accessible :comment, :user_id
end

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

しかし、次の方が良いでしょう(:user_idは一括割り当てではアクセスできません):

@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save
于 2013-01-05T22:12:05.170 に答える
0

ログを見ると、user_idを割り当てようとしていることに関する警告が表示される可能性があります。attr_accessibleを使用する場合は、割り当てるすべての属性を追加する必要があります。変化する

  attr_accessible :comment

  attr_accessible :comment,:user_id
于 2013-01-05T20:13:08.337 に答える
0

どうですか

@comment = Comment.new(params[:comment])
@comment.user = current_user
@comment.post = @post
@comment.save
于 2013-01-05T22:29:15.340 に答える