2010-11-13 52 views
2

假設Post - Comment模型嵌套的資源:form_for with association - 如何提供父母ID?

resources :posts do 
    resources :comments 
end 

應如何app/views/comments/_form.html.haml(ERB也將這樣做)的樣子,這樣它也提供了郵寄到註釋附加到的ID?

目前只有一種方法,我知道是手動添加隱藏的輸入與職位ID。它對我來說很髒。

有沒有更好的方法?我期望導軌能夠理解嵌套的資源並自動將post_id作爲隱藏輸入。

= form_for [@post, @comment] do |f| 
    .field 
    f.label :body 
    f.text_field :body 
    hidden_field_tag :post_id, @post.id 
    .actions 
    = f.submit 'Save' 

編輯:使用Mongoid,沒有ActiveRecord的。

謝謝。

回答

4

帖子的ID實際上會在URL中。如果您鍵入rake routes到你的終端/主機,你會看到你的嵌套資源的模式被定義爲這樣的:

POST /posts/:post_id/comments {:controller=>"comments", :action=>"create"} 

看看由該form_for方法吐出HTML,並專門研究在<form>標記的網址action處。您應該看到類似action="/posts/4/comments"的內容。

假設你已經在你的routes.rb定義resources :comments一次,作爲resources :posts嵌套的資源,那麼它是安全的,你修改CommentsController#create行動,例如:

# retrieve the post for this comment 
post = Post.find(params[:post_id]) 
comment = Comment.new(params[:comment]) 
comment.post = post 

或者你可以簡單地傳遞到params[:post_id]例如comment像這樣:

comment.post_id = params[:post_id] 

我希望這有助於。此外

+0

,如果你最終不得不經常爲此,inherited_resources:

有關嵌套的表格/模型的更多信息,我建議看以下Railscasts寶石自動化爲你的很多關聯管理: https://github.com/josevalim/inherited_resources – Dominic 2010-11-13 18:36:09

+0

它應該與Mongoid一起使用以及? – 2010-11-13 18:38:52