0
<% @parts.each do|x| %>


<% @bbb = Relation.where(part: "#{x}") %>
<%= **@"#{x}"** = @bbb.collect {|x| x.car} %>

<% end %>

3行目の変数をx部分の値@"#{x}"に設定しようとしています。正しい構文が見つかりません。send(x)とx.to_symについて知っています。しかし、各ループのxを@を使用して@変数に設定する方法を知る必要があります。ありがとう!

4

1 に答える 1

2

So you're looking for instance_variable_set

instance_variable_set "@#{x}", @bbb.collect { |x| x.car }

But this is probably not the best way to handle this. Without seeing the code that uses it, its hard to really say, but maybe consider putting the results into a hash: result[x] = @bbb.collect { |x| x.car }

Also note that "#{x}" is the same as x.to_s

Also, it's best to avoid querying models directly in your views (assuming you're doing Rails here, since you appear to be using ActiveRecord), because it mixes presentation with code (you can't take them as separate pieces. It has a tendency to get really ugly), it couples your view to the one use case you initially had (can't present different data in the same view even though it should be presented the same). Consider moving this code into your controller (or even some other object whose responsibility is to manage the querying of this data, leaving your controller responsibilities at just dealing with the request.

于 2012-09-01T20:42:22.080 に答える