Bierc
Bierc

Reputation: 39

Implement a user comment in Rails

Since i'm new in ruby on rails i'm kinda confused with the syntaxes on making a user comments under a users posts, The associations are:

class User < ActiveRecord::Base
  has_many :comments 
  has_many :posts 
end

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user
end

class Comments < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

Im able to make a users post using the @post = current_user.posts.build(postparams)

I have already a user_id in my comments db. Now i'am confuse on how to make the comment belongs_to user so this is the comments_controller

def create
  @comment = @post.comments.create(comment_params)
  redirect_to post_path(@post)
end

if i run the above code it makes a comment under a post but it doesn't belong to a user.

Upvotes: 1

Views: 113

Answers (2)

The F
The F

Reputation: 3734

If your schema is right, this should work in your comments_controller:

def comment_params
  params.require(:comment).permit(:name, :body)
                          .merge(user_id: current_user.id)
end

Simply merge the current user id in your comment params, and you do not need to hack the user_id in your form as a hidden field. This could be a potential security issue.

Upvotes: 1

user3672155
user3672155

Reputation: 1

What are your comment_params? You could add a field to your comment form named user_id with the value of the current user.

Other Option:

Another way to make sure the comment is written by the current user is to add the user after comment new.

def create
  @comment = @post.comments.new(comment_params)
  @comment.user = your_current_user 
  @comment.save
  redirect_to_post_path(@post)
end

Upvotes: 0

Related Questions