2015-02-10 125 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