0

我有以下循环

<% @sub_categories.dropdown_heads.each do |label| %>
    <label for="login"><%= label.head_name %></label>
    <%= select_tag "post[dynam][#{label.head_name}]", options_for_select(generate_option(label)) %>
<% end %>

这是我用于生成下拉菜单的辅助函数

def generate_option opt
    opt.dropdown_lists.inject([]) do |memo, cat|
      memo << [cat.list_name, cat.list_name]
    end
  end

上面的代码将生成以下结果(检查屏幕截图)。

在此处输入图像描述

在我的数据库表中,我有一个名为 content 的列,其中包含类似的数据

{"Style":"convertible","Year":"2010","Color":"green"}

由于上面的代码来自编辑表单,我需要在选择下拉列表中显示所选值我如何解析 json 数据并显示所选值请提供任何建议。

编辑 1

我将线路更改为

<%= select_tag "post[dynam][#{label.head_name}]", options_for_select(generate_option(label)), selected: get_value_for(label.head_name, @post) %>

它没有显示错误,但它没有过滤只是正常显示

我的帮手

def get_value_for(head_name, post)
    content_hash = JSON.parse post.content
    content_hash[head_name]
  end
4

1 回答 1

0

有另一个助手来获取标签的值。

<% @sub_categories.dropdown_heads.each do |label| %>
    <label for="login"><%= label.head_name %></label>
    <%= select_tag "post[dynam][#{label.head_name}]", options_for_select(generate_option(label), get_value_for(label.head_name, @post)) %>
<% end %>


def get_value_for(head_name, post)
  content_hash = ActiveSupport::JSON.decode(post.content)
  content_hash[head_name]
end

我假设您在控制器中设置 @post 并且 Post 模型是您正在编辑的模型并且它具有字段内容

此代码也未经测试。无论如何它应该给你这个想法

于 2013-11-13T18:55:34.090 回答