2016-08-03 118 views
0

我有一個關於form_for嵌套資源的問題。我創建了一些類似博客的內容,包括文章,評論和評論評論(如回覆)。我有一個問題。然後我試着讓評論的那樣: 「重定向到http://localhost:3000/ 過濾器鏈停止爲:get_parent渲染或重定向 完成302找到」form_for嵌套資源(帖子,評論)

徵求意見new.html.erb:

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

我評論控制器:

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 

樁模型:

has_many :comments, as: :commentable 
belongs_to :user 

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

評論型號:

belongs_to :user 

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

路線:

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庫與應用:https://github.com/Dmitry96/dasasd

回答

0

new形式不傳也不post_id也不comment_id參數。它應該是表單動作url或form body中的eather。

我看不到所有的圖片,但我認爲你必須添加父id到表單動作url。現在是/comments,裏面沒有父id參數。它必須是/posts/:post_id/comments/comments/:comment_id/comments

您的形式更改爲:

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

嘿兄弟,謝謝你。我爲這個表單和控制器切換到(comment_params)。它開始工作 – ApecBrah