在一个 Rails 表单中编辑单个类的多个对象的最佳方法是什么?
我正在开发一个 Rails 表单,它允许用户通过一次提交来编辑一个类的许多对象的属性。我最初的直觉是创建一个外部 form_for
块,然后使用 fields_for
迭代其中的项目。
但是,没有任何对象与表单将修改的对象具有一对多关系,因此在我看来,没有任何对象可以正确传递到 form_for
中。
无论如何,我希望看到的是一个同时修改多个对象而不吸引“父”对象的表单示例。也许这会涉及到form_tag
?
(注意:我在 haml 中工作,所以 haml 中的答案会很棒,但没有必要。)
I'm working on a Rails form that will allow the user to edit the attributes of many objects of a class with a single submission. My initial instinct was to create an outer form_for
block and then iterate through the items within it using fields_for
.
However, there is no object that bears a one-many relation to the objects the form will modify, and so it seems to me that there is no object that would be correct to pass into form_for
.
In any case, what I'd like to see is an example of a form that modifies multiple objects simultaneously without appealing to a "parent" object. Perhaps this will involve form_tag
?
(Note: I'm working in haml, so answers in haml would be awesome though unnecessary.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,有一个父对象会让事情变得更容易。
对于许多对象的批量更新,关键是使用正确的输入名称,以便rails将参数解析为数组,即
查看生成的html源以查看文本输入获取的名称属性。如果做得正确,params[:posts] 现在将成为控制器中的哈希值,然后您可以更新它。
http://railscasts.com/episodes/165-edit-multiple 也应该相关
Well, having a parent object will make it easier.
For bulk updates of many objects, the key is to use the right input name so that rails will parse the params as a array, i.e.
Have a look at the generated html source to see what name attribute the text input gets. If this is done right, params[:posts] will now be a hash in the controller which you can then update.
http://railscasts.com/episodes/165-edit-multiple should be relevant too
我的实际情况有一些额外的问题,但这里有一些伪代码,我希望它们能够说明我所采取的方法:
等等。
使用表单助手的
_tag
变体(不需要与 Active Record 模型关联)有点麻烦,但似乎也可以让您更好地控制结果参数的结构。There are some extra wrinkles to my actual situation, but here's some pseudocode that I hope will illustrate the approach I've taken:
And so on.
Using the
_tag
variants of the form helpers, which don't require association with an Active Record model, is a bit of a pain but also seems to give you more control over structure of the resulting parameters.