Ruby でデータを変数名にサブインするにはどうすればよいですか?
概要
それで私は持っています
LanRole.where("lan_id = ?", requestable.id).each do |lan_role| %>
<% @lan_??? = Lan.find(lan_role.lan_id) %>
<li><a data-toggle="tab" href="#lan_info_<%= lan.id %>"><%= lan.name %> INFO</a></li>
どこ ???後でタブに配置できるように、lan_role.id にする必要があります
<div class="tab-content">
<div id="lan_info_<%= lan.id %>" class="tab-pane fade">
<h4><%= @lan_???.name %> INFO</h4>
etc
</div>
しかし、変数変数名を作成してそこにサブ変数を付ける方法がわかりません。
文字列だったらできる
#{lan_role.id}
しかし、それは文字列ではありません。
…エラーを読み間違えました。にあります。
ActionView::Template::Error (undefined local variable or method `lan' for #<#<Class:0x007f7afb9e98a0>:0x007f7afb28aeb0>):
解決策
「変数」変数の場合:
{one: 1, two: 2, three: 3}.each do |name, id|
instance_variable_set("@lan_#{name}", [id, name])
p @lan_one, @lan_two, @lan_three
end
[1, :one]
nil
nil
[1, :one]
[2, :two]
nil
[1, :one]
[2, :two]
[3, :three]
ただし、タブを作成しているので、リンク用と本文用の 2 つのループを作成するだけです。
collection = LanRole.where("lan_id = ?", requestable.id)
# make tabs
collection.each do |role|
role.name
end
# make tab contents
# collection is now loaded it won't hit the database again, at least it shouldn't
collection.each do |role|
role.description
end