2015-02-10 123 views
0

我按照本教程http://www.sitepoint.com/nested-comments-rails/为图像板实现嵌套注释。它运行良好,直到我让“评论”属于“董事会”,然后不得不嵌套我的路线。Rails 4使用嵌套资源嵌套注释表单发生路由错误

这里是我的路线:

Rails.application.routes.draw do 
    root "boards#index" 
    devise_for :users do 
    get '/users/sign_out' => 'devise/sessions#destroy' 
    end 
    resources :boards do 
    resources :comments 
     get '/comments/new/(:parent_id)', to: 'comments#new', as: :new_comment 
     get '/comments/(:parent_id)', to: 'comments#destroy', as: :delete_comment 
     get '/comments/edit/(:parent_id)', to: 'comments#edit', as: :edit_comment 
    end 
end 

这里是我的形式:

<%= form_for [@board, @comment] do |f| %> 
    <% if @comment.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2> 

     <ul> 
     <% @comment.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <%= f.hidden_field :parent_id %> 

    <div class="form-group"> 
    <% if @comment.parent_id == nil %> 
    <%= f.label :title %> 
    <%= f.text_field :title, class: 'form-control' %> 
    <% else %> 
    <% nil %> 
    <% end %> 
    </div> 
    <div class="form-group"> 
    <%= f.radio_button(:user_id, current_user.id) %> 
    <%= f.label(:user_id, "I want to post as myself") %> 
    <%= f.radio_button(:user_id, nil) %> 
    <%= f.label(:user_id, "I want to post anonymously") %> 
    </div> 

    <div class="form-group"> 
    <%= f.label :content %> 
    <%= f.text_area :content, class: 'form-control', required: true %> 
    </div> 

    <div class="form-group"> 
    <%= f.label :image %> 
    <%= f.file_field :image %> 
    </div> 

    <%= f.submit class: 'btn btn-primary' %> 
<% end %> 

这里是我的控制器:

​​

我已经尝试设置自定义路线该表单至少会显示表单,但是当您点击提交按钮时,它会返回“无路由匹配[POST]”/板/ 1 /评论/新“”。如果我到了控制器,然后将相应的“get”改为“post”,那么它会导致表单在按下提交后重新出现,并且没有任何内容被添加到数据库中。我也尝试过按照我的教师建议浅层嵌套我的路线,但这并不奏效。

回答

1

你的主板和评论之间的关联必须是:

board.rb

has_many :comments 

comment.rb

belongs_to :user 

的routes.rb

resources :boards do 
resources :comments, only: [:new, :edit, :destroy] 
end 

这将创造一条路线

new_board_comment GET /boards/:board_id/comments/new(.:format)  comments#new 
edit_board_comment GET /boards/:board_id/comments/:id/edit(.:format) comments#edit 
board_comment  DELETE /boards/:board_id/comments/:id(.:format)  comments#destroy