如何使用Rails3应用程序正确设置嵌套路由



为什么我会得到这样的错误?

undefined method `community_topics_path' for #<#<Class:0x00000009d79098>:0x00000009d70a38>
Extracted source (around line #1):
1: <%= form_for @community_topic, :html => { :class => 'form-horizontal' } do |f| %>
2:   <div class="control-group">
3:     <%= f.label :community_id, :class => 'control-label' %>
4:     <div class="controls">

耙子路由显示我将'to_param'用于社区的ID,但我尚未定义:routes.rb中的community_id。我想知道为什么耙路路线显示:community_id。这可能是因为我为社区模型使用" to_param"?这就是为什么它会自动检测并替换:ID为:community_id?

new_community_topic GET    /communities/:community_id/topic/new(.:format)      community_topics#new

Routes.rb

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

views/communities/_form.html.erb

<%= form_for @community_topic, :html => { :class => 'form-horizontal' } do |f| %>
.......
  <div class="form-actions">
    <%= f.submit nil, :class => 'btn btn-primary' %>
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                community_topic_path, :class => 'btn' %>
  </div>
<% end %>

更新!!!

**耙路|grep community_topic

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

在使用嵌套路由时,您必须将community传递到form_for

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

upd :或@community_topic.community如果您未设置@community

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

您可以观看这一集的Railscast,以完全了解嵌套资源。情节使用Rails 2进行示例,但您应该理解概念。

最新更新