如何在form_for中使用数组?
我有一个用户模型,其中包含一个名为 text1 的字段。在 users/new 表单中,我希望该文本有 4 个单独的文本框。在我的模型中,我将从这些框中获取值并将它们作为逗号分隔值连接在一起并将它们存储在数据库中。为了让你理解,这就是我想要的。
<input type="text" name="user[text1][]" />
<input type="text" name="user[text1][]" />
<input type="text" name="user[text1][]" />
<input type="text" name="user[text1][]" />
如何使用 form_for 辅助方法获得它?现在请不要担心模型中的访问器方法,这一切都已解决。非常感谢。
I've got a user model which contains a field called, lets say, text1. In the users/new form I want to have 4 individual text boxes for this text1. In my model I will take values from these boxes and concatenate them together as comma separated values and store them in the DB. To give you an understanding, this is what I want.
<input type="text" name="user[text1][]" />
<input type="text" name="user[text1][]" />
<input type="text" name="user[text1][]" />
<input type="text" name="user[text1][]" />
How do I get this using form_for helper method? For now please don't worry yourself about the accessor method in the model, that is all taken care of. Thanks a ton.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
向您的
User
模型添加一些虚拟属性在您的视图代码中使用新属性而不是 text1
Add few virtual attributes to your
User
modelIn your view code use the new attributes instead of text1
前面的答案给出了一个解决方案,所以我只是提供一些背景知识,说明为什么您所要求的内容无法按照您希望的方式工作。
您确实可以创建一个具有多个同名输入字段的表单,并且将发布该数据。但是,当 Rails 收到帖子时,它会自动参数化帖子数据和/或 url 参数。它本质上是在 & 上分裂的。并将键/值对分配给 params 哈希。这样做的结果是 params[:user][:text1] (来自您的示例)将具有它遇到的 user[text1] 最后一个实例的值,因为它只是对现有键的值分配。您可能想要深入研究 ActiveRecord 多参数分配以了解日期时间属性的工作原理,因为它们与您的用例类似。
The previous answer gives a solution, so I am just providing some background as to why what you are asking for does not work they way you might hope.
You can indeed create a form with multiple input fields of the same name, and that data will be posted. However, when rails receives the post it automatically parameterizes the post data and/or url parameters. It essentially splits on the & and assigns the key/value pairs to the params hash. The outcome of this is that params[:user][:text1] (from your example) will have the value of the last instance of the user[text1] it encountered, since it is simply a value assignment to an existing key. You might want to dig into ActiveRecord multiparameter assignments to get an idea of how datetime attributes work, since they are similar to your use-case.
我正在研究类似的东西,听起来也许序列化就是您正在寻找的东西。不幸的是,我的问题还没有解决,所以我无法提供更具体的信息。
I am working on something similar and it sounds like maybe serialization is what you are looking for. Unfortunately I don't have my issues solved yet, so I can't provide anything more concrete.