-1

I want to create a form for "Comments" route which is a member of Article Resources:

 resources :articles do
  member do
   post 'comments'
  end
 end

I want the comment form to be in Articles#Show page. The problem i got an error:

First argument in form cannot contain nil or be empty

If the for is like this:

<div>
  <%= form_for @comm do |c| %>
  <%= c.label :Your_comment %>
  <%= c.text_area :commBody %>
  <%= c.submit 'submit' %>
  <% end %>
</div>

So how to do it ?

steve
  • 257
  • 4
  • 12

2 Answers2

1

If this is your controller,

def show
  @article = Article.find(params[:id])
end

and you want to create a form for a new Comment related to @article that points to POST /articles/3/comments:

<%= form_for([@article, Comment.new], as: :article, url: comments_article_path(@article)) do |f| %>
  <%= f.label :body %>
  <%= f.text_area :body %>
  <%= f.submit 'Submit' %>
<% end %>

Don't forget to add accepts_nested_attributes_for :comments in the Article model. And also don't forget to setup the whitelisted params in the ArticleController.

Another thing: don't use abbreviations for your variable names. Use @article and @comment, not @art and @comm.

zwippie
  • 15,050
  • 3
  • 39
  • 54
  • Thanks @zwippie. I did it and it is working. I did tried it without ACCEPT_NESTED method and it is also working. So what is the disadvantage if I do not use this method? – steve Jan 18 '16 at 14:33
1
#config/routes.rb
resources :articles do
   post :comment, on: :member #-> url.com/articles/:id/comment
end

#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
   def show
      @article = Article.find params[:id]
      @comment = @article.comments.new
   end
end

#app/views/articles/show.html.erb
Comment:
<%= form_for [@article, @comment], url: article_comment_path(@article) do |c| %>
   <%= c.label "Your Comment" %>
   <%= c.text_area :commBody %>
   <%= c.submit %>
<% end %>
Richard Peck
  • 76,116
  • 9
  • 93
  • 147