Implement a user comment in Rails -
since i'm new in ruby on rails i'm kinda confused syntaxes on making user comments under users posts, 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 make users post using @post = current_user.posts.build(postparams)
i have user_id in comments db. i'am confuse on how make comment belongs_to user comments_controller
def create @comment = @post.comments.create(comment_params) redirect_to post_path(@post) end
if run above code makes comment under post doesn't belong user.
if schema right, should work in comments_controller:
def comment_params params.require(:comment).permit(:name, :body) .merge(user_id: current_user.id) end
simply merge current user id in comment params, , not need hack user_id in form hidden field. potential security issue.
Comments
Post a Comment