你的表單定義應該是這樣的:
<%= form_for [@story, Comment.new] do |form| %>
<div id="body">
<%= form.text_field :body %>
</div> <% form.hidden_field :user_id, :value => @current_user.login %>
<p>
<%= submit_tag 'Comment' %>
</p>
<% end %>
表單使用POST /comments
,而不是POST /stories/:story_id/comments
行動。 它應該拋出一個關於丟失的POST /comments
路線的例外,這就是爲什麼我不確定我的解決方案。但由於某些原因,您的路線擁有comments
資源。所以它知道如何創建URL,但它不知道它應該包含/stories/:story_id
部分。
這裏的另一件事是你將current_user傳遞給表單。這是不好的,因爲任何知道如何使用螢火蟲或任何其他網站管理員工具的人都可以將此欄位更改爲(例如)您的登入名稱並發表評論,就好像它是你一樣。您應該在控制器的創建操作中分配用戶字段。
還有一個。我真的不明白爲什麼你需要所有這些路線。如果這是我的應用程序,路線會是這個樣子:
Telling_tales::Application.routes.draw do
resource :session
resource :stories #really can't see why you need a singular route here
resource :user
resources :users do
get 'register' => 'create', :on => :collection #maps to 'users#create'
end
resources :stories do
resources :comments
collection do
get ':login' => 'show' #it seems illogical to place this route under `stories` namespace
#if you wanted to display stories of one particular user, you'd better make it `/users/:user_id/stories`
get 'search'
end
root :to => 'stories#index'
end
在this和this指南看看。
我有資源:故事不 資源:評論 結束 – gleb