私は問題を抱えています、私はこの帰属をコメントモデルにします:
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