2011-06-28 16 views
1

我有最近升級應用程式導軌3問題的@story = Story.find(PARAMS [:story_id])在導軌3

在我的意見控制器I有

def create 
    @cuser = @current_user 
    @story = Story.find(params[:story_id]) 
    @story.comments.create(:user_id => @cuser.login,:body => params[:comment][:body]) 
    respond_to do |format| 
    format.html { story_path} 
    format.js 
    end 
end 

story.rbhas_many :commentscomment.rbbelongs_to :story

當我嘗試創建一個評論,我收到了

Couldn't find Story without an ID 

這用於工作。任何想法,爲什麼它不再?還有什麼可能影響它呢?這可能是一個路由問題?

回答

0

是的,它可能是一個路由問題。你可能已經發現路由DSL已經改變了,我猜你已經搞亂了。看起來你曾經有過的路線類似

`map.resources:故事

和你(也許)取代了喜歡的東西

resources :stories do 
     resources :comments do 
     collection do 
      post :create 
     end 
     end 
    end 

我只是猜測,但我認爲這會給排序您所看到的錯誤 - 你需要像

resources :stories do 
    resources :comments 
end 

的路線,它會自動生成創建的路線,或者如果要指定更PR ecisely

resources :stories do 
    resources :comments do 
    member do 
     post :create 
    end 
    end 
end 
+0

我有資源:故事不 資源:評論 結束 – gleb

0

我假設你有以下的路由配置:

resources :stories do 
    resources :comments 
end 

如果是這樣的話,你必須使用params[:story_id]

@story = Story.find(params[:story_id]) 
+0

我使用PARAMS [:story_id現在,但它並不能幫助 – gleb

1

你的表單定義應該是這樣的:

<%= 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 

thisthis指南看看。

+0

我使用PARAMS [:story_id現在。這沒什麼區別 – gleb

+0

@gleb - 我們可以看看這是從哪裏來的。我認爲那個bassneck正在做某件事。也許story_id永遠不會在表單中傳遞。 – natedavisolds

+0

這是表格 <%= form_for Comment.new do | form | %>

<%= form.text_field :body %>
<%form.hidden_​​field:USER_ID,:值=> @ current_user.login%>

<%= submit_tag '評論' %>

<% end %> – gleb