[英]Loop through hash in rails
I have some functionality where I client can create custom fields, what I'm trying to do now is to loop through that data but I can't seem to get it to work.我有一些功能,我的客户可以创建自定义字段,我现在要做的是循环遍历这些数据,但我似乎无法让它工作。
Here are the params when we create or update a record, I've removed some as I'm only trying to loop through custom_fields_attr
这是我们创建或更新记录时的参数,我已经删除了一些,因为我只是想循环遍历
custom_fields_attr
Parameters: {... "custom_fields_attr"=>{"1"=>"testing12", "2"=>"", "3"=>"", "4"=>""}}, ...}
I have the following code:我有以下代码:
<!-- start of custom fields -->
<% if Contact.has_custom_fields %>
<div class="form-block">
<h2 class="txt-title-alt">Custom Fields</h2>
<% Contact.custom_fields.in_groups_of(2).each do |field| %>
<div class="l-row-block clearfix">
<% field.each do |item| %>
<div class="l-06col l-ml-12col l-md-12col">
<div class="field field_display l-row-block clearfix">
<p class="like_p clearfix">
<strong class="l-06col">
<%= item.label %>:
</strong>
<span class="value l-06col">
<%= item.value %>
</span>
</p>
</div>
</div>
<% end %>
</div>
<% end %>
</div>
<% end %>
<!-- end of custom fields -->
I have a custom fields table which is where we get the label from but I need to get the value from the custom_fields_attr
hash我有一个自定义字段表,我们从中获取 label 但我需要从
custom_fields_attr
hash 中获取值
Edit The output of @contact.custom_fields_attr
is编辑
@contact.custom_fields_attr
的 output 是
>> @contact.custom_fields_attr
=> {"1"=>"test field123"}
Instead of doing field.each do |item|
而不是做
field.each do |item|
try field.each do |key, value|
尝试
field.each do |key, value|
. . This lets you access the
key
and value
of each hash pair in your block.这使您可以访问块中每个 hash 对的
key
和value
。
Could you tell me what is the output of Contact.custom_fields
?你能告诉我
Contact.custom_fields
的 output 是什么吗?
Can you tell, how the client is creating the custom fields, because if they are params send to the controller, you can access the params in the controller, in this case you want "custom_fields_attr", you can call it by params["custom_fields_attr"] and then to loop through it params["custom_fields_attr"].each do |key, value|
你能告诉,客户端是如何创建自定义字段的,因为如果它们是发送到 controller 的参数,你可以访问 controller 中的参数,在这种情况下你想要“custom_fields_attr”,你可以通过 params[“custom_fields_attr”来调用它"] 然后循环遍历它
params["custom_fields_attr"].each do |key, value|
calling in each time key = "1" and value = "testing12" then key = "2" and value = "" and etc.每次调用 key = "1" 和 value = "testing12" 然后 key = "2" 和 value = "" 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.