I am learning Rail (4.2 installed) and working on a social network simulation application. I have setup many relationships between the user and the post, and now I am trying to add comments on the posts too. After several attempts and ending with the following setup:
User Model
has_many: post, dependent: deleted has_many: Comments, via:
post model
related_to: user has_many: comments
Comment Model
related_to: user
The comment post has been started from the show page, so < Strong> Post Controller :
def show @comment = co Mment.new end
The question now is: Comments Controller , what is the correct way to create a new record? I tried down and many other people, but without success
def make @comment = current_user.posts.comment.new (comment_params) @ comment.save redirect_to users_path end
<>
(from current_user devise Is)
Besides, how can I choose related posts for a comment?
Thanks
You make a relationship on post
Describe each comment
, which is related to post
. " In your case, you want to create a foreign key on comment
, then every comment will be
related_
one Specific post
. So, you add related_to: post
to your comment
model.
Therefore, your models are created:
class users & lt; ActiveRecord :: Base has has_many: posts, dependent :: deleted has_many: Comments, through :: Post the end posts of posts & lt; ActiveRecord :: Base is_to: User has_many: Comments and Class Comments & lt; ActiveRecord :: Base is_to: User is_to: post end
Then, to create a comment
, you would want to do one of two tasks in your controller: / P>
-
Load
related to comment
as you are making a parameter through the URI. Pass -
Post
in the form that calls tocreate
method oncomment
Does.
I personally prefer to load posts
from a parameter in the URI, because you have permission for authorization As far as possible, check it comment can be added to the
post
- for example
>> method
comments controller to create will look like this:
< / Div> def create @ post = post.find (post_id_param) # you Want authorization logic for "current_user a comment # Can post this ", and maybe" Is there any current user? "@comment = @ post.comments.build (comment_params) if @ comment.save redirect_to posts_path (@post) else # Display errors and return to comment @ Erres = @ comment. Errors Render: New End and Private Def post_id_param params.require (: Post_id) end def comment_params params.require (: comment) .permit (...) # Acceptable acceptable commentary at the end of the params
No comments:
Post a Comment