【问题标题】:form_for nested resources(post, comment)form_for 嵌套资源(帖子、评论)
【发布时间】:2017-08-21 18:55:31
【问题描述】:

我有一个关于带有嵌套资源的 form_for 的问题。我创建了类似博客的东西,在 cmets 上有帖子、cmets、cmets(如回复)。我有一个问题。然后我尝试发表评论:“重定向到http://localhost:3000/ 过滤器链因 :get_parent 呈现或重定向而停止 已完成 302 找到”

用于 cmets 的 new.html.erb:

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

我的 cmets 控制器:

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您的new 表单既没有传递post_id 也没有传递comment_id 参数。它应该在表单操作 url 或表单正文中。

    我看不到所有图片,但我认为您必须将父 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 %>
    

    【讨论】:

    • 嘿兄弟,谢谢。我切换到这种形式并在控制器中切换到(comment_params)。它开始工作
    猜你喜欢
    • 2011-01-03
    • 2011-01-16
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多