form_for with association - 如何提供父ID?

时间:2010-11-13 17:39:50

标签: ruby-on-rails ruby rest view formbuilder

假设Post - Comment模型具有嵌套资源:

resources :posts do
  resources :comments
end

app/views/comments/_form.html.haml(erb也会如何)看起来应该是这样的,它还提供了将评论附加到帖子的ID?

目前我只知道一种方法是手动添加带有帖子ID的隐藏输入。它看起来很脏。

还有更好的方法吗?我希望rails能够理解嵌套资源并自动将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。

感谢。

1 个答案:

答案 0 :(得分:4)

帖子的ID实际上在URL中。如果在终端/控制台中键入rake routes,您将看到嵌套资源的模式定义如下:

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

查看form_for方法吐出的HTML,并专门查看action代码的<form>网址。您应该看到action="/posts/4/comments"之类的内容。

假设您resources :comments中的routes.rb一次,作为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]

我希望这会有所帮助。

有关嵌套表单/模型的更多信息,我建议您观看以下Railscast:

相关问题