I'm trying to add comments to a Post model
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user #should this be has_one :user instead?
....
How do I set up my Comment new and creation actions to get both current_user as well as the current post?
guides.rubyonrails.org suggested
Controller:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
View
<%= form_for([@post, @post.comments.build]) do |f| %>
...
However this only seems to be aiming to associate with the post and not also the user. How can I set up both associations?
I assume you have a current_user()
method somewhere in your controller.
So this should do it:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
@comment.user = current_user
@comment.save
redirect_to post_path(@post)
end
Deradon answered the question well but I prefer to have that logic within the new comment form itself. For example, instead of calling those variables you can have:
app/views/comments/_form.html.erb:
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.hidden_field :post_id, value: @post.id %>
This assumes of course that your new comment form is embedded within the 'post show' page, so that @post is available:
app/views/posts/show.html.erb:
<body>
<%= render @post %>
<%= render 'comments/_form' %>
</body>
This will add post_id and user_id directly into the db for a new comment. Also, don't forget to make an index for those foreign keys so the database has quicker access. If you don't know how, google it!