json解析rails以在编辑表单rails中显示选择下拉列表中的结果

时间:2013-11-13 18:43:13

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我有以下循环

<% @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

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

enter image description here

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

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

由于以上代码来自编辑表单,我需要在select下拉列表中显示所选值。如何解析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

1 个答案:

答案 0 :(得分: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模型是您正在编辑的模型,并且它具有字段内容

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