I have a problem, i make this atribbuition i comment model:
class Comment < ActiveRecord::Base
attr_accessible :comment
belongs_to :post
belongs_to :user
and this in user model
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
has_many :posts
has_many :comments
but this dont works:
<% post.comments.each do |comment| %>
<div id="comments" >
<%= comment.user.email %>
<%= comment.comment %>
</div>
<%end%>
appear the error:
undefined method `email' for nil:NilClass
please what is the problem, in the create of the comment i make the atribbuition so , look:
@comment = @post.comments.create(params[:comment],:user_id => current_user.id)
how i solve this error, please-
I try this:
@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))
and this:
@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save
dont works
same error:
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%>
i dont know what is wrong my model comment have :user_id
attr_accessible :comment,:user_id,:post_id
and my form make is this
<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 %>
please help me i dont know where is the error, the db is migrate correctly
UPDATE:
Have a before_filter and need login to see the page to comment, so have current_user, and i reset the bd and make new comments logged, i test meet getting the comment.user_id and get the id of the user but the method comment.user.email dont works, i will post the , the comment model is:
attr_accessible :comment,:user_id,:post_id
belongs_to :post
belongs_to :user
validates_presence_of :comment ,:on =>:create
the model user is:
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
May be using
@postinstead ofpostin view file will help?