2010-11-13 53 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