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 Modelrelated_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
No comments:
Post a Comment