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 に答える