Ruby-on-rails – Rails: getting data from a table for each iteraction of a loop

model-view-controllerrubyruby-on-rails

I have a loop (for item in @dataset) and I want, in each iteration, to get different data from another table and make some operations that will be printed in the view. I cant't get this data from the dataset used in the loop.

How can I do this according to MVC? I can put the code into the loop, in the view, but I think it's horrible.

Must I use a helper for do this, and call the function from the view?

Best Answer

If you have one table, and want to get data from another table, usually this is in the situation of a has_many relation. For example, we have @people (Person model), and each person has_many addresses (Address model). In those cases the best thing to do is this

# Controller
@people = Person.find(:all, :include => :addresses)
...

# View
@people.each do |p|
  p.addresses.each do |address|
    ...

If your data is not just normal database tables (maybe you get it from a web service or so on), then a good thing to do is to build all the data in the controller ahead-of-time, then pass that to the view. Something like this

# Controller
@people = Person.find(:all)
@people.each do |p|
  # attach loaded data to the person object in controller
  p.addresses = Address.load_from_somewhere_by_name(p.name)
...

This way the view code stays clean, like this:

# View
@people.each do |p|
  p.addresses.each do |address|
    ...