尝试使用嵌套路由创建表单时,为什么会出现NoMethod错误?

时间:2012-12-23 16:48:04

标签: ruby-on-rails ruby-on-rails-3 routing

我正在使用rails3 在嵌套路由中加载新操作时,我得到NoM​​ethod错误。

  

#<#:0x0000000a067ef8>

的未定义方法`community_community_topics_path'

我该如何解决这个问题?

_form.html.erb

<%= form_for ([@community, @community_topic]), :html => { :class => 'form-horizontal' } do |f| %>

  <div class="control-group">
    <%= f.label :title, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_field :title, :class => 'text_field' %>
    </div>
  </div>
  <div class="control-group">
    <%= f.label :body, :class => 'control-label' %>
    <div class="controls">
      <%= f.text_area :body, :class => 'text_area' %>
    </div>
  </div>

  <div class="form-actions">
    <%= f.submit nil, :class => 'btn btn-primary' %>
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                community_topics_path, :class => 'btn' %>
  </div>
<% end %>

的routes.rb

resources :communities, :path => "shop", do
    resources :community_topics, :path => "topic", :as => :'topic'
end

耙路线| grep community_topics

   community_topic_index GET    /shop/:community_id/topic(.:format)          community_topics#index
                         POST   /shop/:community_id/topic(.:format)          community_topics#create
     new_community_topic GET    /shop/:community_id/topic/new(.:format)      community_topics#new
    edit_community_topic GET    /shop/:community_id/topic/:id/edit(.:format) community_topics#edit
         community_topic GET    /shop/:community_id/topic/:id(.:format)      community_topics#show
                         PUT    /shop/:community_id/topic/:id(.:format)      community_topics#update
                         DELETE /shop/:community_id/topic/:id(.:format)      community_topics#destroy

2 个答案:

答案 0 :(得分:4)

您应该在路线文件中使用复数形式的“主题”:

resources :communities, :path => "shop", do
  resources :community_topics, :path => "topics", :as => :'topics'
end

这样做,您会看到rake routes会将第一条路线从community_topic_index更改为community_topics,让您使用community_topics_path

注意:您可能还想使用“商店”而不是“购物”,这样您的网址格式将与Rails通常的方式一致:http://example.com/shops等。

答案 1 :(得分:1)

您可以手动指定您的网址。只需将它传递给url param,无论你希望表单从rake路由转到什么路径。从您的路线文件看起来,community_topic_index_url就是您的后期行动。

<%= form_for :community_topic, url: community_topic_index_url, :html => { :class => 'form-horizontal' } do |f| %>