3

undefined method当我只是尝试查看表单(不提交)时,我有一个 simple_form_for new_comment 导致浏览器中出现comments_path'` 错误

_form.html.slim

= simple_form_for new_comment, :remote => true do |f|

这是部分的,所以传递的局部变量来自hacks脚手架的显示页面

show.html.slim - 黑客

= render partial: "comments/form", locals: { new_comment: @new_comment } if user_signed_in?

我在 hacks 控制器中定义了@new_comment

hacks_controller.rb

  def show
    @hack = Hack.find(params[:id])
    @comments = @hack.comment_threads.order('created_at DESC')
    @new_comment = Comment.build_from(@hack, current_user.id, "") if user_signed_in?
                           #build_from is a method provided by the acts_as_commentable_with_threading gem
  end

为什么 new_comment 要路由到 comments_path?我什至没有提交表格。

路线.rb

  root 'hacks#index'

  concern :commentable do
    resources :comments, only: [:create, :update, :destroy]
  end

  resources :hacks, concerns: [:commentable]
  resources :users

  devise_for :users, :skip => [:sessions, :registration]
  devise_for :user,  :path => '', :path_names => { :sign_in => "login", 
                                                  :sign_out => "logout", 
                                                  :sign_up => "register", 
                                                  :account_update => "account-settings" }
4

2 回答 2

1

由于您的评论嵌套在 hack 中,因此您需要评论和 hack。所以,试试这个

show.html.slim

= render partial: "comments/form", locals: { new_comment: @new_comment, hack: @hack } if user_signed_in?

_form.html.slim

= simple_form_for [hack, new_comment], :remote => true do |f|
于 2014-09-13T09:02:12.733 回答
0

路线

首先,我不相信您的表单会路由到index操作

调用comments_path取决于您在路由中定义的 CRUD 操作。具体来说,form_for将自动填充该create操作,Rails 将尝试从resource您在routes.rb文件中定义的一组基础路由中调用该操作:

在此处输入图像描述

注意上面的例子,它会如何/photos使用POST动词?这可能看起来是发送到“索引”操作(photos_path) - 但实际上,凭借 HTTP 动词,它将发送到create操作


形式

simple_form_for基本上是一个抽象form_for

在刚刚显示的示例中,虽然没有明确指出,但我们仍然需要使用 :url 选项来指定表单将被发送到哪里。但是,如果传递给 form_for 的记录是资源,则可以进一步简化,即它对应于一组 RESTful 路由,例如使用 config/routes.rb 中的资源方法定义。在这种情况下,Rails 将简单地从记录本身推断出适当的 URL

基本上,form_for尝试url从它拥有的对象构建要提交的对象。您有一个嵌套路由,这意味着您需要提供嵌套对象:

= simple_form_for [hack, new_comment], :remote => true do |f|

这应该将路径发送到hacks_comments_path,这是您想要的,对吧?或者,您可以规定url选项:

= simple_form_for new_comment, remote: true, url: hacks_comments_path(hack) do |f|

请注意这两个修复程序如何需要hack局部变量?

= render partial: "comments/form", locals: { new_comment: @new_comment, hack: @hack } if user_signed_in?

使固定

您需要将nested路径传递给simple_form_for帮助程序(如上所述)

于 2014-09-13T09:25:37.990 回答