Rails 嵌套路由下地表单提交不成功

sensi · February 04, 2015 · Last by sensi replied at February 10, 2015 · 3401 hits

路由:

resources :products, :shallow => true do
  resources :articles
end

表单:

<%= form_for @article, url: new_product_article_path(@article) do |f| %>

    <p>
       <%= f.label "title" %></br>
       <%= f.text_field :title %>
    </p>

    <p>
       <%= f.label "content" %></br>
       <%= f.text_area :content %>
    </p>

    <p>
       <%= f.submit %>
    </p>
<% end %>

log:

tarted GET "/products/1/articles/new" for 127.0.0.1 at 2015-02-04 21:12:28 +0800
Processing by ArticlesController#new as HTML
  Parameters: {"product_id"=>"1"}
  Rendered articles/new.html.erb within layouts/application (2.2ms)
Completed 500 Internal Server Error in 7ms

ActionView::Template::Error (No route matches {:action=>"new", :controller=>"articles", :product_id=>nil} missing required keys: [:product_id]):
    1: <h1>New article</h1>
    2: 
    3: <%= form_for @article, url: new_product_article_path(@article) do |f| %>
    4: 
    5:  <p>
    6:        <%= f.label "title" %></br>
  app/views/articles/new.html.erb:3:in `_app_views_articles_new_html_erb___2302585143041901570_70250353575640'

(No route matches {:action=>"new", :controller=>"articles", :product_id=>nil} missing required keys: [:product_id]): product_id =》nil,这个参数是怎么通过 form_for 传递的?

articles_controller.rb 裡面的 new 方法寫對了沒有? @article = @product.articles.build

<%= form_for [@product, @article] ..... %>

new_x_path(xx) 木有这种写法 你实在想传 id 可以 url: "#{new_x_path}?id=xx"

#2 楼 @yangman_wenzhu 想知道这些知识点在哪里,我在 guides 里也没找到这些复杂的方法 api 里没见呀!

#1 楼 @blacktulip 然后提示 undefined method `articles' for nil:NilClass

#6 楼 @sensi 你給的代碼片段太少了,請把整個 project 推到 github 上看看

You need to Sign in before reply, if you don't have an account, please Sign up first.