DavidL
DavidL

Reputation: 915

Cannot create comments from Post view

I have a model Post that has_many :comments. The form that will post the comment will be shown along with the post in posts/show.html.erb. I have a comments_controller that should handle the creation of comments. Searching on google, I found

<%= form_for([@post, Comment.new], :controller => 'comments', :action => 'create') do |f| %>

But this doesn't work. How do I do this ?

Upvotes: 1

Views: 548

Answers (1)

James Martin
James Martin

Reputation: 96

class Post < ActiveRecord::Base
  has_many :comments

  accepts_nested_attributes_for :comments
#...

class Comment < ActiveRecord::Base
  belongs_to :post
#...

Then in the form

form_for @post do |f|
  f.fields_for :comments do |c|
    c.text_field :title
    #...
  f.submit

this would create the associated object through active record's accepts_nested_attributes_for, which doesn't require a separate comments_controller. you are submitting to the posts controller, which is handling creating the associated object during the update of the post.

with a comments_controller, you could do one of two things:

send item_id as a param to comments_controller#new, grab the item, then build the new comment from it

@post = Post.find(params[:item_id); @comment = @post.comments.build

put the post_id in a hidden field on the form and just create the comment as normal

# in the controller
@comment = Comment.create(params[:comment])

# in the view
form_for @comment do |f|
  f.text_field :title
  #...
  f.hidden_field :post_id, value: @post.id

Upvotes: 1

Related Questions