3

undefined method単純にフォームを表示しようとする (送信しない) と、ブラウザーで comments_path '` エラーが発生する simple_form_for new_comment があります。

_form.html.slim

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

これは部分的なものであるため、渡されるローカル変数は、hacks scaffold の show ページからのものです。

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

0

ルート

indexまず、フォームがアクションにルーティングされるとは思わない

への呼び出しcomments_pathは、ルートで定義した CRUD アクションに依存します。具体的には、Rails がファイルで定義した一連のベース ルートから呼び出そうとするアクションにform_for自動的に入力されます。createresourceroutes.rb

ここに画像の説明を入力

上記の例からわかるように、動詞を/photos使用するとどうなるでしょうか? POSTこれは、「インデックス」アクション ( ) に送信されているように見えるかもしれませんがphotos_path、実際には、HTTP 動詞のおかげで、createアクションに送信されます。


simple_form_forは基本的に次の抽象化ですform_for:

上記の例では、明示的には示されていませんが、フォームの送信先を指定するために :url オプションを使用する必要があります。ただし、form_for に渡されるレコードがリソースである場合、つまり、たとえば config/routes.rb の resources メソッドを使用して定義された一連の RESTful ルートに対応する場合は、さらに単純化できます。この場合、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 に答える