Aluxzi
Aluxzi

Reputation: 177

Associate post comment with a user

I have an application that allows users to comment on a post.

rails generate model Comment commenter:string body:text post:references

How can I change it so the commenter is set as the user who posted the comment

Upvotes: 0

Views: 944

Answers (2)

Aluxzi
Aluxzi

Reputation: 177

I finally found how to solve the problem.

rails generate model Comment user_id:integer body:text listing:references

add :user_id to attr_accessible in the \app\models\comments.rb file then add the hidden attribute to the comment form:

<%= f.hidden_field :user_id, :value => current_user.id %>

Then use <%= comment.user.id %> and/or <%= comment.user.name %>

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44675

You need to make association:

rails generate model Comment author_id:integer body:text post:references

class Comment < ActiveRecord::Base

  belongs_to :post
  belongs_to :author, class_name: <User or whatever your user model is called>, foreign_key: :author_id

end

class User < ActiveRecord::Base
  has_many :comments, foreign_key: :author_id
end

You will also need to assign this value when new comment is created:

#Comment controller? Hard to say how it is being saved from the code you posted. :P

  def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    if @comment.save
      ...
    end
  end

Upvotes: 1

Related Questions