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


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

<% end %>

I'm trying to set the variable in line 3 to the x part value @"#{x}". I can't find the right syntax. I know about send(x) and x.to_sym. But I need to know how to set x in the each loop to an @variable with @. Thanks!

San Backups
  • 515
  • 9
  • 17

1 Answers1

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.

Joshua Cheek
  • 30,436
  • 16
  • 74
  • 83
  • Sure but I need 15 rep points and don't have those yet. I'm new. I'm open to advise on how to use this system better. – San Backups Sep 01 '12 at 21:34