ApecBrah ApecBrah - 4 months ago 18
Ruby Question

form_for nested resources(post, comment)

I have one question about form_for with nested resources. I create something like blog, with posts,comments, comments on comments(like replies).And I have an issue. Then I try to make comment it: "Redirected to http://localhost:3000/
Filter chain halted as :get_parent rendered or redirected
Completed 302 Found"

new.html.erb for comments:

<div class= "container" %>
<%= form_for @comment do |f| %>
<%= f.input :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
</div>


My comments controller:

before_filter :get_parent

def new
@comment = @parent.comments.build
end

def create
@comment = @parent.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to posts_path(@comment.post), :notice => 'Thank you for your comment!'
else
render :new
end
end

private

def comment_params
params.require(:comment).permit(:body, :title, :user_id, :commentable_id, :commentable_type)
end


def get_parent
@parent = Post.find_by_id(params[:post_id]) if params[:post_id]
@parent = Comment.find_by_id(params[:comment_id]) if params[:comment_id]

redirect_to root_path unless defined?(@parent)
end
end


post model:

has_many :comments, as: :commentable
belongs_to :user

def post
commentable.is_a?(Post) ? commentable : commentable.post
end


comment model:

belongs_to :user

belongs_to :commentable, polymorphic: true
has_many :comments, :as => :commentable


routes:

resources :posts do
resources :comments
end

resources :comments do
resources :comments
end


post_show.html.erb

<h1><%= @post.title %></h1>

<div class="body">
<%= @post.body %>
</div>

<h2>Comments</h2>

<p><%= link_to 'Add a Comment', new_post_comment_path(@post) %></p>

<ul class="comment_list">
<%= render :partial => 'comments/comment', :collection => @post.comments %>
</ul>


github repo with app: https://github.com/Dmitry96/dasasd

Answer

Your new form does not pass neither post_id nor comment_id parameter. It should be eather in the form action url or in the form body.

I can not see all the picture, but I think you have to add parent id to the form action url. It is /comments now, has no parent id parameter in it. It must be /posts/:post_id/comments or /comments/:comment_id/comments.

Change your form to:

<%= form_for [@parent, @comment] do |f| %>
  <%= f.input :title %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>