Joel Grannas
Joel Grannas

Reputation: 2016

Associated tables: Join or Include with Rails

I am feeling a bit slow when it comes to rails and the Active Record associations... I have two tables.

Table = Rings
Table = Variations with foreign_key => "ring_id".

class Ring < ActiveRecord::Base
      has_many :variations
end

class Variation < ActiveRecord::Base
      belongs_to :ring
end

So in my "index/list" view i want to display all the rings, and both the variations, and i was thinking it would be possible to do this through one SQL query... however, i have tried the join and the include methods and i think i am just not understanding how they work properly.

So my question is, how would i write a query in my controller, that would pull my "title" and "value" column values from the "variations" and combine them into one simple object for easy looping? Or do i have to loop through all rings and look up the variation values during the loop?

thanks

Upvotes: 2

Views: 899

Answers (2)

niiru
niiru

Reputation: 5112

In your controller:

@rings = Ring.includes(:variations).all

In index.html.erb:

@rings.each do |ring|
  ...
  ring.variations.each do |variation|
    ...
  end
end

The includes portion of the query will prevent Rails from repeatedly querying the database as you loop through and render your rings and variations in the view.

Upvotes: 2

Idan Arye
Idan Arye

Reputation: 12633

You need to use the includes method: Ring.inclues(:variations). Then the variation will be loaded along with the rings in a single SQL query.

For more info: http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations

Upvotes: -1

Related Questions