form_for 与关联 - 如何提供父 ID?
假设带有嵌套资源的 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。
谢谢。
Assuming the Post
- Comment
model with the nested resources:
resources :posts do
resources :comments
end
How should the app/views/comments/_form.html.haml
(erb will do as well) look like so that it also provides id of the post to attach the comment to?
Current only one way I know is to manually add hidden input with the post id. It looks dirty to me.
Is there any better way? I expected rails to understand the nested resource and automatically include the post_id
as a hidden input.
= 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'
EDIT: Using Mongoid, not ActiveRecord.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
帖子的 ID 实际上位于 URL 中。如果您在终端/控制台中输入
rake paths
,您将看到嵌套资源的模式定义如下:看一下
form_for< 吐出的 HTML /code> 方法,并具体查看
假设您在
routes.rb
中仅定义 一次resources :comments
,作为resources :posts< 的嵌套资源/code>,那么您可以安全地修改
CommentsController#create
操作:或者您可以简单地将
params[:post_id]
传递给comment< /code> 实例如下:
我希望这有帮助。
有关嵌套表单/模型的更多信息,我建议观看以下 Railscast:
The ID of the post will actually be in the URL. If you type
rake routes
into your terminal/console, you will see that the pattern for your nested resource is defined as such:Take a look at the HTML that is spit out by the
form_for
method, and look specifically at theaction
url of the<form>
tag. You should see something likeaction="/posts/4/comments"
.Assuming that you've defined
resources :comments
only once in yourroutes.rb
, as a nested resource ofresources :posts
, then it is safe for you to modify theCommentsController#create
action as such:Or you can simply pass
params[:post_id]
tocomment
instance like so:I hope this helps.
For more information on nested forms/models, I recommend watching the following Railscasts: