views:

15

answers:

1

I have 3 models defined:

  • Palette (has many swatches)
  • Swatch (has one color)
  • Color (?)

How should the tables / associations be defined so that from the Palette object you can collect all the colors, for example:

@colors = @palette.swatches.colors

(Swatches currently store a color_id, palette_id, plus some related info such as sort_order, etc.)

A: 

I think this will get you the results you want.

# palette table:
# id INT
class Palette < ActiveRecord::Base
    has_many :swatches
    has_many :colors, :through => :swatches
end

# swatch table:
# id INT
# palette_id INT
# color_id INT
class Swatch < ActiveRecord::Base
    belongs_to :palette
    belongs_to :color
end

By using the :through parameter, you can then access the palette's colors directly.

@colors = @palette.colors
Thaliant
Thanks, that works :) I was missing Swatch belongs_to :color, which seems unintuitive.
meleyal