作者:单莼de笑脸 | 来源:互联网 | 2023-09-25 09:09
IhaveamodelProduct,whichhasapropertiesattribute.Itstoresitinasingledatabasecolumna
I have a model Product, which has a properties attribute. It stores it in a single database column as a hash (following http://api.rubyonrails.org/classes/ActiveRecord/Store.html)
我有一个模型Product,它有一个属性属性。它将它作为哈希存储在单个数据库列中(在http://api.rubyonrails.org/classes/ActiveRecord/Store.html之后)
class Product
How can I create dynamic form fields for this property attribute (which is a hash)? I'm interested in ideologically correct way of doing this ("rails way"). I guess that there is need to use fields_for helper. But I do not fully understand how to do it. Tell me the correct way of solving this problem, please.
如何为此属性属性(这是一个哈希)创建动态表单字段?我对意识形态正确的做法感兴趣(“轨道方式”)。我想有需要使用fields_for帮助器。但我不完全明白该怎么做。请告诉我解决这个问题的正确方法。
In result, I'd like to get a working form like shown on image.
结果,我想得到一个像图像所示的工作表格。
Where a user can add unlimited number of fields and give any property names and its values.
用户可以添加无限数量的字段并提供任何属性名称及其值。
3 个解决方案
8
The rails way needn't include the limitation of using a single table, ideally, you can do this in a very rails way with 2 tables. Moving on.
rails方式不需要包括使用单个表的限制,理想情况下,您可以使用2个表以非常有轨的方式执行此操作。继续。
You shouldn't use Active Record :store
for this purpose in my opinion.
在我看来,您不应该使用Active Record:store来实现此目的。
That implementation is ideal for situations where the developers need to store model metadata that is flexible in-code but well-defined at any given point of time. Which is to say, you need to specify keys in the model.
对于开发人员需要存储灵活的代码但在任何给定时间点定义良好的模型元数据的情况,该实现非常理想。也就是说,您需要在模型中指定键。
There is another pit-fall, you can't run SQL queries on the resulting serialized text that is saved.
还有另一个陷阱,您无法对保存的结果序列化文本运行SQL查询。
If you insist, you can do this:
如果你坚持,你可以这样做:
In your model:
在你的模型中:
class Product
In the view:
在视图中:
<%= form_for @product do |f| %>
<% f.object.prop_hash.each do |k,v| %>
<%= text_field 'product[prop_hash][][name]', k %>
<%= text_field 'product[prop_hash][][value]', v %>
<% end %>
<% end %>
Then you can also add an 'add another property' link which should use JS to insert another pair of inputs with the names product[prop_hash][][name]
and product[prop_hash][][value]
respectively.
然后你还可以添加一个'添加另一个属性'链接,该链接应该使用JS分别插入名为product [prop_hash] [] [name]和product [prop_hash] [] [value]的另一对输入。
Long ago I had rolled a custom implementation for metadata which saves the keys in serialized XML, for one reason - it can be queried in SQL. The link to my blog article http://geniitech.tumblr.com/post/14916592782/storing-metadata-as-xml-hash-in-ror
很久以前,我已经推出了元数据的自定义实现,它将密钥保存在序列化的XML中,原因之一是 - 它可以在SQL中查询。我的博客文章http://geniitech.tumblr.com/post/14916592782/storing-metadata-as-xml-hash-in-ror的链接