gpt4 book ai didi

ruby-on-rails - 带关联的 form_for - 如何提供父 ID?

转载 作者:数据小太阳 更新时间:2023-10-29 08:41:25 25 4
gpt4 key购买 nike

假设 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。

谢谢。

最佳答案

帖子的 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:

关于ruby-on-rails - 带关联的 form_for - 如何提供父 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4173832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com