form_for嵌套资源(发布,评论)

时间:2016-08-03 21:34:45

标签: ruby-on-rails ruby

我有一个关于使用嵌套资源的form_for的问题。我创建类似博客的东西,包括帖子,评论,评论评论(如回复)。我有一个问题。然后我尝试发表评论:“重定向到http://localhost:3000/ 过滤链暂停为:get_parent呈现或重定向 完成302发现“

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 repo with app:https://github.com/Dmitry96/dasasd

1 个答案:

答案 0 :(得分:0)

您的new表单既未通过post_id也未通过comment_id参数。它应该在表单动作URL或表单体中。

我无法看到所有图片,但我认为您必须将父ID添加到表单操作网址。现在为/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 %>