开发者

How to make an association across 3 tables with activerecord / rails?

开发者 https://www.devze.com 2023-01-10 03:09 出处:网络
I have 3 models defined: Palette (开发者_JAVA百科has many swatches) Swatch (has one color) Color (?)

I have 3 models defined:

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.)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消