Comments that belong_to Post and belong_to User

Go To StackoverFlow.com

1

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?

2012-04-05 22:36
by Rapture


6

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
2012-04-05 22:47
by Deradon
And the form should be built like: <%= formfor([@post, @post.comments.build]) do |f| %> and not just <%= formfor(@comment) do |f| %> - Rapture 2012-04-05 22:51
Thanks! I was able to implement this - Rapture 2012-04-10 18:35


0

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!

2013-12-01 21:06
by RobinSH
Ads