Skip to content
This repository was archived by the owner on Jan 7, 2021. It is now read-only.

Association basics.textile

mhhwang2002 edited this page Mar 6, 2011 · 34 revisions

ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ๊ด€๊ณ„(Active Record Association)์— ๋Œ€ํ•œ ์•ˆ๋‚ด

๋ณธ ์•ˆ๋‚ด๋ฌธ์„œ๋Š” ์•กํ‹ฐ๋ธŒ ๋ ˆ์ฝ”๋“œ์˜ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๊ด€๊ณ„(associations) ํŠน์„ฑ๋“ค์„ ๋‹ค๋ฃจ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ฌธ์„œ์˜ ์ฐธ๊ณ ๋ฅผ ํ†ตํ•ด์„œ ๋‹น์‹ ์€

  • ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ ๋ชจ๋ธ๋“ค ๊ฐ„์˜ ๊ด€๊ณ„ ์„ ์–ธ
  • ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ ๊ด€๊ณ„๋“ค์˜ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ํ˜•ํƒœ์— ๋Œ€ํ•œ ์ดํ•ด
  • ๊ด€๊ณ„ ์ƒ์„ฑ์„ ํ†ตํ•œ ์ถ”๊ฐ€๋œ ๋ชจ๋ธ ํ•จ์ˆ˜ ๋ฐ ๋ฐ์ดํ„ฐ์˜ ์‚ฌ์šฉ
    ๋“ฑ์„ ํ•˜์‹ค ์ˆ˜ ์žˆ๊ฒŒ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.
    endprologue.

์™œ ``๊ด€๊ณ„โ€™โ€™์ธ๊ฐ€?

์™œ ์šฐ๋ฆฐ ๋ชจ๋ธ๋“ค์‚ฌ์ด์— ๊ด€๊ณ„๊ฐ€ ํ•„์š”ํ•œ ๊ฒƒ์ผ๊นŒ์š”? ๊ทธ๊ฒƒ์€ ๊ด€๊ณ„๊ฐ€ ์—ฐ๊ฒฐ๋œ ๋ชจ๋ธ๋“ค์„ ๋ณด๋‹ค ๊ฐ„๋‹จํ•˜๊ณ  ์‰ฝ๊ฒŒ ๋™์‹œ์— ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด์„œ ๊ฐ„๋‹จํ•œ ๋ ˆ์ผ์ฆˆ ์‘์šฉํ”„๋กœ๊ทธ๋žจ์ด ๊ณ ๊ฐ๋ชจ๋ธ๊ณผ ์ฃผ๋ฌธ๋ชจ๋ธ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ฉ์‹œ๋‹ค. ๊ฐ๊ฐ์˜ ๊ณ ๊ฐ์€ ๋‹ค๋ฅธ ๋งŽ์€ ์ฃผ๋ฌธ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋ฉด, ๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ์ด ๋ชจ๋ธ๋“ค์˜ ์„ ์–ธ์ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

class Customer < ActiveRecord::Base
end

class Order < ActiveRecord::Base
end

์—ฌ๊ธฐ์„œ, ์ด๋ฏธ ์กด์žฌํ•˜๋Š” ํ•œ ๊ณ ๊ฐ์˜ ์ƒˆ๋กœ์šด ์ฃผ๋ฌธ์„ ์ถ”๊ฐ€ํ•˜๊ธธ ์›ํ•˜๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ด…์‹œ๋‹ค. ์šฐ๋ฆฌ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ•ด์•ผ ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

@order = Order.create(:order_date => Time.now,
:customer_id => @customer.id)

๋˜๋Š” ๊ณ ๊ฐ์„ ์‚ญ์ œํ•˜๊ณ , ๊ทธ ๊ณ ๊ฐ ๊ด€๋ จ ๋ชจ๋“  ์ฃผ๋ฌธ๋„ ์‚ญ์ œํ•ด์•ผ ํ•œ๋‹ค๋ฉด ์ด๋Ÿฐ ์ฝ”๋“œ๋ฅผ ๋ณด์‹œ๊ฒŒ ๋  ๊ฒ๋‹ˆ๋‹ค.

@orders = Order.where(:customer_id => @customer.id)
@orders.each do |order|
order.destroy
end
@customer.destroy

ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ ๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, ์ด ๋‘ ๊ณ ๊ฐ๊ณผ ์ฃผ๋ฌธ ๋ชจ๋ธ ์‚ฌ์ด์— ๊ด€๊ณ„๊ฐ€ ์žˆ์Œ์„ ์„ ์–ธํ•ด ์คŒ์œผ๋กœ์จ ์ผ๊ด„ ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•ด ์ง‘๋‹ˆ๋‹ค. ์—ฌ๊ธฐ ์ˆ˜์ •๋œ ์ฝ”๋“œ๋ฅผ ๋ณด์‹œ์ฃ .

class Customer < ActiveRecord::Base
has_many :orders, :dependent => :destroy
end

class Order < ActiveRecord::Base
belongs_to :customer
end

์ด ์ˆ˜์ •์„ ํ†ตํ•ด์„œ ์šฐ๋ฆฌ๋Š” ํ•œ ๊ณ ๊ฐ์˜ ์ƒˆ๋กœ์šด ์ฃผ๋ฌธ ์ƒ์„ฑ์ด ์‰ฌ์›Œ์กŒ์Œ์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์•Œ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (๋–จ๋  ํ•œ์ค„์ด์˜ˆ์š”.)

@order = @customer.orders.create(:order_date => Time.now)

ํ•œ ๊ณ ๊ฐ๊ณผ ๊ด€๋ จ๋œ ๋ชจ๋“  ์ฃผ๋ฌธ์˜ ์‚ญ์ œ๋Š” ๋”๋”์šฑ ์‰ฌ์›Œ ์กŒ์–ด์š”. ๋‹ค์Œ์„ ๋ณด์„ธ์š”.

@customer.destroy

๋‹ค์–‘ํ•œ ๊ด€๊ณ„์˜ ์ข…๋ฅ˜๋ฅผ ๋” ๋ฐฐ์šฐ์‹œ๊ธธ ์›ํ•˜์‹ ๋‹ค๋ฉด, ๋‹ค์Œ ์•ˆ๋‚ด์„œ์˜์ ˆ(section)์„ ์ฝ์–ด ์ฃผ์„ธ์š”. ๋‹ค์Œ์— ์†Œ๊ฐœ๋˜๋Š” ๊ฒƒ๋“ค๋กœ๋Š” (1) ๊ด€๊ณ„์™€ ๊ด€๋ จ๋œ ๊ธฐ๋ฒ•๋“ค, ๋ฌ˜์ˆ˜๋“ค, (2)๋ ˆ์ผ์ฆˆ์—์„œ ์ œ๊ณต๋˜๋Š” ๊ด€๊ณ„์™€ ์—ฐ๊ด€๋œ ํ•จ์ˆ˜๋“ค, ๊ทธ๋ฆฌ๊ณ  ์˜ต์…˜๋“ค์„ ์™„์ „ํ•˜๊ฒŒ ์„ค๋ช…ํ•˜๋Š” ์ฐธ๊ณ ์ž๋ฃŒ๊ฐ€ ๋˜๊ฒ ์Šต๋‹ˆ๋‹ค.

๊ด€๊ณ„์˜ ์œ ํ˜•๋“ค

๋ ˆ์ผ์ฆˆ์—์„œ, ๊ด€๊ณ„ ๋Š” ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ ๋ชจ๋ธ๋“ค๊ฐ„์˜ ์—ฐ๊ด€์„ ๋งํ•ฉ๋‹ˆ๋‹ค. ๊ด€๋ จ์€ ๋งคํฌ๋กœ ์Šคํƒ€์ผ์˜ ํ˜ธ์ถœ๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ์–ด์„œ, ์šฐ๋ฆฌ๊ฐ€ ์„ ์–ธ๋งŒ ํ•˜๋ฉด ๋ชจ๋ธ๋“ค ์‚ฌ์ด์— ๋งŒ๋“ค์–ด ์ง‘๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ํ•œ ๋ชจ๋ธ์ด ๋‹ค๋ฅธ ๋ชจ๋ธ์— ์†ํ•ด์žˆ๋‹ค๋Š” ๋œป์˜ belongs_to ๊ด€๊ณ„๋ฅผ ์„ ์–ธํ•˜๋ฉด ๋‹น์‹ ์€ ์ฃผ์—ด์‡ (primary key)-์™ธ๋ถ€์—ด์‡ (foreign key) ์ •๋ณด๋ฅผ ์ด๋“ค ๋ชจ๋ธ๋“ค์˜ ์˜ˆ(์ธ์Šคํ„ด์Šค, instance)๋“ค ์‚ฌ์ด์— ์ƒ์„ฑํ•˜๋ผ๋Š” ๋ช…๋ น์„ ๋ ˆ์ผ์ฆˆ์— ํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๊ฒŒ๋‹ค๊ฐ€ ์ด๋“ค ๋ชจ๋ธ์— ์—ฌ๋Ÿฌ ์œ ์šฉํ•จ์ˆ˜๋“ค์ด ์ถ”๊ฐ€๋˜์–ด ์‚ฌ์šฉํ• ์ˆ˜ ์žˆ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ๋ ˆ์ผ์ฆˆ์€ ๋‹ค์Œ ์—ฌ์„ฏ ๊ฐ€์ง€์˜ ๊ด€๊ณ„ํ˜•์„ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค.

  • belongs_to
  • has_one
  • has_many
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many

๊ฐ๊ฐ์˜ ์˜๋ฏธ๋กœ๋Š” belongs_to B๋Š” B โ€œ๊ฐ์ฒด์˜ ์˜ˆ์— ์†ํ•ด์žˆ๋‹คโ€, has_one B๋Š” B โ€œ๊ฐ์ฒด์˜ ์˜ˆ๋ฅผ ํ•˜๋‚˜ ๊ฐ–๋Š”๋‹คโ€, has_many B๋Š” B โ€œ๊ฐ์ฒด์˜ ์˜ˆ๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ ๊ฐ–๋Š”๋‹คโ€, has_many: through B๋Š” B โ€œ๊ฐ์ฒด์˜ ์˜ˆ๋ฅผ ํ†ตํ•ด์„œ ์—ฌ๋Ÿฌ๊ฐœ ๊ฐ–๋Š”๋‹คโ€, has_one :through B๋Š” B โ€œ๊ฐ์ฒด์˜ ์˜ˆ๋ฅผ๋ฅผ ํ†ตํ•ด์„œ ํ•˜๋‚˜ ๊ฐ–๋Š”๋‹คโ€, ๋งˆ์ง€๋ง‰์œผ๋กœ has_and_belongs_to_many B๋Š” B โ€œ๊ฐ์ฒด์˜ ์˜ˆ์— ์†ํ•ด ์žˆ์œผ๋ฉด์„œ ๋™์‹œ์— B ๊ฐ์ฒด์˜ ์˜ˆ๋ฅผ ๋งŽ์ด ๊ฐ–๋Š”๋‹คโ€ ์ž…๋‹ˆ๋‹ค.

์ด ์ดํ›„๋กœ, ๋‹น์‹ ์€ ์—ฌ๋Ÿฌ ํ˜•ํƒœ์˜ ๊ด€๊ณ„๋ฅผ ์–ด๋–ป๊ฒŒ ์„ ์–ธํ•˜๊ณ  ์‚ฌ์šฉํ•˜๋Š” ์ง€๋ฅผ ๋ฐฐ์šฐ๊ฒŒ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด์— ์•ž์„œ์„œ ๊ฐ๊ฐ์˜ ๊ด€๋ จ ์œ ํ˜•์ด ์‚ฌ์šฉ๋˜๋Š” ์ƒํ™ฉ์„ ๊ฐ„๋žตํ•˜๊ฒŒ ๋จผ์ € ์„ค๋ช…๋“œ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค.

belongs_to ๊ด€๋ จ

ํ•˜๋‚˜์˜ belongs_to ๊ด€๋ จ์€ ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ์˜ 1: 1 ์—ฐ๊ด€์„ ์ •์˜ํ•˜๋Š”๋ฐ, ํ•œ ๋ชจ๋ธ์˜ ์˜ˆ๊ฐ€ ๋‹ค๋ฅธ ๋ชจ๋ธ์˜ ์˜ˆ์— ์†ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด์„œ, ๋‹น์‹ ์˜ ์‘์šฉ ํ”„๋กœ๊ทธ๋žจ์ด ์•ž์„œ ์„ค๋ช…ํ•œ ๊ณ ๊ฐ๊ณผ ์ฃผ๋ฌธ์„ ํฌํ•จํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ์ด๋•Œ ํ•˜๋‚˜์˜ ์ฃผ๋ฌธ์ด ์˜ค์ง ํ•˜๋‚˜์˜ ๊ณ ๊ฐ์—๋งŒ ๊ด€๋ จ๋˜์–ด ์žˆ๋‹ค๋ฉด ๋‹น์‹ ์€ ์ฃผ๋ฌธ ๋ชจ๋ธ์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ ์–ธํ•˜๊ฒŒ ๋ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

class Order < ActiveRecord::Base
belongs_to :customer
end

belongs_to Association Diagram

has_one ๊ด€๋ จ

has_one ๊ด€๋ จ ๋˜ํ•œ ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ์˜ 1:1 ๊ด€๊ณ„๋ฅผ ๊ทœ์ •ํ•ฉ๋‹ˆ๋งŒ ๋‹ค๋ฅธ ์˜๋ฏธ์™€ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ–์ด๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์ด ๊ด€๊ณ„๋Š” ํ•˜๋‚˜์˜ ๋ชจ๋ธ์˜ ์ผ์˜ˆ๊ฐ€ ๋‹ค๋ฅธ ๋ชจ๋ธ์˜ ์ผ์˜ˆ๋ฅผ ์†Œ์œ ํ•˜๊ฑฐ๋‚˜ ํฌํ•จํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด๋‹น์‹ ์˜ ์‘์šฉํ”„๋กœ๊ทธ๋žจ์—์„œ ๊ตฌ๋งค๋ถ€์„œ์—์„œ ์‚ฌ์šฉ๋˜๋ฉฐ ๋‚ฉํ’ˆํšŒ์‚ฌ๋ฅผ ๊ด€๋ฆฐํ•œ๋‹ค๊ณ  ์นฉ์‹œ๋‹ค. ๊ฐ ๋‚ฉํ’ˆํšŒ์‚ฌ ๊ฐ๊ฐ ํ•˜๋‚˜์˜ ๊ณ„์ •์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋ฉด, ์šฐ๋ฆฌ๋Š” ์ด๋‚ฉํ’ˆํšŒ์‚ฌ๋ชจ๋ธ์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ ์–ธํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

class Supplier < ActiveRecord::Base
has_one :account
end

has_one Association Diagram

has_many ๊ด€๋ จ

has_many ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ 1:๋‹ค(ๅคš:๋งŽ์Œ) ๊ด€๊ณ„๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค. ์•„๋งˆ๋„ ๋‹น์‹ ์€ ์ด ๊ด€๊ณ„๊ฐ€ +belong_to+๊ด€๊ณ„์˜ ๋ฐ˜๋Œ€ ๊ด€์ ์ด๋ผ๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ด ๊ด€๊ณ„๋Š” ๋‹ค๋ฅผ ๋ชจ๋ธ์˜ ์˜ˆ๋ฅผ ํ•˜๋‚˜๋„ ๊ฐ€์ง€๊ณ  ์žˆ์ง€ ์•Š๊ฑฐ๋‚˜ ๋˜๋Š” ๋ณต์ˆ˜๊ฐœ ๊ฐ€์ง€๊ณ  ์žˆ์„ ๋•Œ(์ฆ‰, 0๊ฐœ์—์„œ ์—ฌ๋Ÿฌ๊ฐœ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์„ ๋•Œ) ์— ์‚ฌ์šฉํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ๊ณ ๊ฐ๊ณผ ์ฃผ๋ฌธ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋‹น์‹ ์˜ ์‘์šฉ ํ”„๋กœ๊ทธ๋žจ์—์„œ ๊ณ ๊ฐ ๋ชจ๋ธ์ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ ์–ธ๋  ์ˆ˜ ์žˆ๊ฒ ์Šต๋‹ˆ๋‹ค.

class Customer < ActiveRecord::Base
has_many :orders
end

์ฃผ์˜: has_many B ๊ด€๊ณ„๋ฅผ ์„ ์–ธํ•˜๋Š” ๊ฒฝ์šฐ์—orders ์™€ ๊ฐ™์ด B๊ฐ€ ๋ณต์ˆ˜ํ˜•์˜ ์ด๋ฆ„์„ ๊ฐ–๊ฒŒ๋˜๋Š” ๊ฒƒ์„ ์ฃผ๋ชฉํ•ด ์ฃผ์„ธ์š”.

has_many Association Diagram

has_many : through ๊ด€๊ณ„

has_many : through ๊ด€๊ณ„๋Š” ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ์˜ ๅคš:ๅคš ๊ด€๊ณ„๋ฅผ ์„ค์ •ํ•  ๋•Œ ์ข…์ข… ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ์ด ๊ด€๊ณ„๋Š” ๋‹ค๋ฅธ ๋ณต์ˆ˜(0ํฌํ•จ)๊ฐœ์˜ ๋ชจ๋ธ์„ ์ œ3์˜ ๋ชจ๋ธ์„ ํ†ตํ•ด์„œ ๊ฐ€์ง€๊ฒŒ ๋จ์„ ๋งํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ๋‚ด๊ณผ ์˜์‚ฌ๊ป˜์„œ ํ™˜์ž๋“ค์„ ์˜๋ฃŒ ๊ฒ€์ง„ํ•˜๋Š” ์ƒํ™ฉ์„ ์ƒ๊ฐํ•ด ๋ด…์‹œ๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ ์˜๋ฃŒ ๊ฒ€์ง„์ด ์˜ˆ์•ฝ์„ ํ†ตํ•ด์„œ๋งŒ ๊ฐ€๋Šฅํ•˜๊ธฐ์—, ์ด์— ์ƒ์‘ํ•˜๋Š” ๊ด€๊ณ„๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜ ๋  ์ˆ˜ ์žˆ๊ฒ ์Šต๋‹ˆ๋‹ค.

class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end

class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end

has_many :through Association Diagram

์—ฐ๊ฒฐ๋ชจ๋ธ ์ง‘ํ•ฉ์€ API๋ฅผ ํ†ตํ•ด์„œ ๊ด€๋ฆฌ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ๋‚ด๊ณผ ์˜์‚ฌ ๊ฐ์ฒด ์˜ˆ physician์—๋Š” patients API๊ฐ€ ์žˆ๋Š”๋ฐ ์ด๊ฒƒ์— ๋‹ค๋ฅธ ์ง‘ํ•œ patients๋ฅผ ๋Œ€์ž…ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ์„ ๋ณด์‹œ์ฃ .

physician.patients = patients

์ƒˆ๋กœ์šด ์—ฐ๊ฒฐ ๋ชจ๋ธ๋“ค์€ ์ƒˆ๋กญ๊ฒŒ ์—ฐ๊ด€๋œ ๊ฐ์ฒด ์˜ˆ๋“ค๋กœ ์ƒ์„ฑ๋˜๊ณ , ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค์˜ ํ–‰์ด ์‚ฌ๋ผ์ง„๋‹ค๋ฉด ๊ด€๋ จ ๊ฐ์ฒด๋“ค๋„ ์‚ฌ๋ผ์งˆ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๊ฒฝ๊ณ : ์—ฐ๊ฒฐ ๋ชจ๋ธ์˜ ์ž๋™ ์‚ญ์ œ๋Š” ์ง์ ‘์ ์ด์–ด์„œ ํŒŒ๊ดด ๋˜๋ถ€๋ฆ„ ํ•จ์ˆ˜(destroy callback)์˜ ํ˜ธ์ถœ์ด ์—†์Œ์„ ์ฃผ์˜ํ•ด ์ฃผ์„ธ์š”.

has_many :through ๊ด€๊ณ„๋Š” ์ค‘์ฒฉ๋œ has_many ๊ด€๊ณ„๋ฅผ ๊ฐ„๋žตํ•˜๊ฒŒ ํ•˜๋Š” "์ง€๋ฆ„๊ธธ"๋กœ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉ๋˜๊ณค ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด ๋งŒ์•ฝ ํ•˜๋‚˜์˜ ๋ฌธ์„œ๊ฐ€ ์—ฌ๋Ÿฌ ์ ˆ์„ ๊ฐ€์ง€๊ณ  ์žˆ๊ณ , ํ•˜๋‚˜์˜ ์ ˆ์€ ๋งŽ์€ ๋ฌธ๋‹จ์„ ๊ฐ€์ง€๊ณ  ์žˆ์„๋•Œ ๋งŒ์•ฝ ํ•œ๋ฌธ์„œ์˜ ๋ชจ๋“  ๋ฌธ๋‹จ์˜ ๋‹จ์ˆœ ์ง‘ํ•ฉ์„ ์–ป๊ธธ ํฌ๋งํ•œ๋‹ค๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ค์ •์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

class Document < ActiveRecord::Base
has_many :sections
has_many :paragraphs, :through => :sections
end

class Section < ActiveRecord::Base
belongs_to :document
has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
belongs_to :section
end

With :through => :sections specified, Rails will now understand:

@document.paragraphs

has_one :through ๊ด€๋ จ

has_one :through ๊ด€๋ จ์€ ๋˜ ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ์˜ 1:1 ์—ฐ๊ด€์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. ์ด ๊ด€๋ จ์€ ์„ ์–ธ ๋ชจ๋ธ์ด ์ œ์‚ผ์˜ ๋ชจ๋ธ์„ ํ†ตํ•ด์„œ ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ ๊ด€๋ จ์„ ๊ฐ–๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ๊ฐ๊ฐ์˜ ๋‚ฉํ’ˆํšŒ์‚ฌ๊ฐ€ ํ•˜๋‚˜์˜ ๊ณ„์ •์„ ๊ฐ–๊ณ , ๊ฐ ๊ณ„์ •์€ ๊ณ„์ •๋‚ด์—ญ์„ ๊ฐ€์ง€๊ณ  ์žˆ์„๋–„์—, ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ชจ๋ธ์„ ์ƒ์„ฑํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

class Supplier < ActiveRecord::Base
has_one :account
has_one :account_history, :through => :account
end

class Account < ActiveRecord::Base
belongs_to :supplier
has_one :account_history
end

class AccountHistory < ActiveRecord::Base
belongs_to :account
end

has_one :through Association Diagram

has_and_belongs_to_many ๊ด€๋ จ

has_and_belongs_to_many ๊ด€๋ จ์€ ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ๋‹คๅคš:ๅคš ์—ฐ๊ฒฐ์„ ์‚ฌ์ด์— ๊ทธ ์–ด๋–ค ๋ชจ๋ธ๋„ ์—†์ด ์ง์ ‘ ์ƒ์„ฑํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์‘์šฉ ํ”„๋กœ๊ทธ๋žจ์ด ๋ถ€ํ’ˆ๊ณผ ์ด์˜ ์กฐ๋ฆฝํ’ˆ์„ ํฌํ•จํ•˜๋Š”๋ฐ, ์กฐ๋ฆฝํ’ˆ์€ ๋งŽ์€ ๋ถ€ํ’ˆ์„ ๊ฐ€์ง€๋ฉด, ํ•œ ๋ถ€ํ’ˆ์€ ๋งŽ์€ ๋ถ€ํ’ˆ์— ์‚ฌ์šฉ๋œ๋‹ค๋ฉด, ์šฐ๋ฆฌ๋Š” ๋‹ค์Œ์˜ ๋ชจ๋ธ์„ ์„ ์–ธํ•˜๊ฒŒ ๋œ๋‹ค.

class Assembly < ActiveRecord::Base
has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end

has_and_belongs_to_many Association Diagram

belongs_to ์™€ has_one ์˜ ์„ ํƒ

๋งŒ์•ฝ ๋‹น์‹ ์ด ๋‘ ๋ชจ๋ธ ์‚ฌ์ด์˜ 1:1 ์—ฐ๊ด€์„ ์„ค์ •ํ•˜๊ณ ์ž ํ•˜๊ณ , ํ•œ ๋ชจ๋ธ์—๊ฒŒ๋Š” belongs_to ๋ฅผ ๋‹ค๋ฅธ ๋ชจ๋ธ์—๋Š” has_one ๋ฅผ ์„ค์ •ํ•ด์•ผ ํ•  ๊ฒฝ์šฐ, ์–ด๋–ค ๋ชจ๋ธ์„ ์–ด๋–ป๊ฒŒ ์„ ํƒํ•ด์•ผ ํ• ๊นŒ์š”?

๊ตฌ๋ณ„๋ฒ•์œผ๋กœ๋Š” ์–ด๋””์— ์™ธ๋ถ€์—ด์‡ (foreign key)๋ฅผ (์ด๊ฒƒ์€+belongs_to+ ๊ด€๊ณ„๋ฅผ ์„ ์–ธํ•˜๋Š” ๊ฐ์ฒด์˜ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ํ…Œ์ด๋ธ”์— ๋ถ€์ฐฉ๋œ๋‹ค) ๋„ฃ์„ ๊ฒƒ์ธ์ง€์— ๋‹ฌ๋ ค์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ ‡์ง€๋งŒ ๋‹น์‹ ์€ ์‹ค์žฌ ๋ฐ์ดํ„ฐ์˜ ์˜๋ฏธ ์ƒ๊ฐํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค. has_one ๊ด€๊ณ„๋Š” ์–ด๋–ค ์‚ฌ๋ฌผ์ด ๋‹น์‹ ์˜ ๊ฒƒ์ด๋ผ๋Š” ๊ฒƒ์„ ๋งํ•˜๋ฉฐ ๊ทธ ์‚ฌ๋ฌผ์€ ๋‹น์‹ ์— ์†ํ•ด์žˆ์Œ์„ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ๋‚ฉํ’ˆ ํšŒ์‚ฌ๊ฐ€ ๊ณ„์ •์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฒƒ์ด ๊ณ„์ •์ด ๋‚ฉํ’ˆํšŒ์‚ฌ๋ฅผ ๊ฐ€์ง€๋Š” ๊ฒƒ๋ณด๋‹ค ๋” ๊ทธ๋Ÿด๋“ฏ ํ•˜์ง€ ์•Š๋‚˜์š”? ๋‹ค์Œ์˜ ์˜ˆ๋ฅผ ๋ณด์‹œ์ฃ .

class Supplier < ActiveRecord::Base
has_one :account
end

class Account < ActiveRecord::Base
belongs_to :supplier
end

์ƒ์„ฑ๋œ ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜ ์ฝ”๋“œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ƒ๊ธฐ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

class CreateSuppliers < ActiveRecord::Migration
def self.up
create_table :suppliers do |t|
t.string :name
t.timestamps
end

create_table :accounts do |t| t.integer :supplier_id t.string :account_number t.timestamps end end def self.down drop_table :accounts drop_table :suppliers end

end

์ฃผ์˜: t.integer :supplier_id ์˜ ์‚ฌ์šฉ์€ ์™ธ๋ถ€ ์—ด์‡ ์˜ ์ด๋ฆ„์„ ๋ช…ํ™•ํ•˜๊ฒŒ ํ•œ๋‹ค. ํ˜„์žฌ ๋ ˆ์ผ์ฆˆ ๋ฒ„์ „์—์„œ๋Š” ๋‹น์‹ ์€+t.references :supplier+์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌ์ฒด์ ์ธ ๊ตฌํ˜„์„ ์ถ”์ƒํ™” ํ• ์ˆ˜ ์žˆ๋‹ค.

has_many :through ์™€ has_and_belongs_to_many ์˜ ์„ ํƒ

๋ ˆ์ผ์ฆˆ๋Š” ๋ชจ๋ธ๋“ค๊ฐ„์— ๋‘๊ฐœ์˜ ๅคš:ๅคš ๊ด€๊ณ„๋ฅผ ์„ ์–ธํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ์ค‘ ๊ฐ„๋‹จํ•œ ๋ฐฉ๋ฒ•์€ has_and_belongs_to_many ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ธ๋‹ค, ์ด ๋ฐฉ๋ฒ•์€ โ€œ์ง์ ‘์ โ€์œผ๋กœ ๊ด€๊ณ„๋ฅผ ๋งŒ๋“ค๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

class Assembly < ActiveRecord::Base
has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end

๋‘๋ฒˆ์งธ ๅคš:ๅคš ๊ด€๊ณ„๋ฅผ ์ •์˜ํ•˜๋Š” ๋ฐฉ๋ฒ•์ธ has_many :through์€ ์—ฐ๊ฒฐ๋ชจ๋ธ์„ ํ†ตํ•ด์„œ โ€œ๊ฐ„์ ‘์ โ€์œผ๋กœ ๊ด€๊ณ„๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.

class Assembly < ActiveRecord::Base
has_many :manifests
has_many :parts, :through => :manifests
end

class Manifest < ActiveRecord::Base
belongs_to :assembly
belongs_to :part
end

class Part < ActiveRecord::Base
has_many :manifests
has_many :assemblies, :through => :manifests
end

๊ฐ€์žฅ ๊ธฐ๋ณธ์ด ๋˜๋Š” ์›์น™์ค‘ ํ•˜๋‚˜๋Š”, ์šฐ๋ฆฌ๊ฐ€ ์—ฐ๊ฒฐ ๋ชจ๋ธ์„ ๋งŒ๋“ค๋•Œ์— ์ด๊ฒƒ์ด โ€œ๋…๋ฆฝ๋œโ€ ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผ๋˜์–ด์•ผ ํ•  ๊ฒฝ์šฐ์—๋Š”+has_many :through+๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ์ข‹๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋งŒ์•ฝ, ์šฐ๋ฆฌ๊ฐ€ ๊ทธ ์–ด๋–ค ๊ฒƒ๋„ ์—ฐ๊ฒฐ ๋ชจ๋ธ ์ž์ฒด๊ฐ€ ํ•„์š” ์น˜ ์•Š๋”๋ฉด+has_and_belongs_to_many+ ๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ๋” ๋‹จ์ˆœํ•œ ๋ฐฉ๋ฒ•์ด๊ณ  ๋”ฐ๋ผ์„œ ๋ฐ”๋žŒ์งํ•ฉ๋‹ˆ๋‹ค(ํ•˜์ง€๋งŒ ์ด๋ฐฉ๋ฒ•๋„ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์—ฐ๊ฒฐํ…Œ์ด๋ธ”(joining table)์ด ์ƒ์„ฑ๋œ๋‹ค๋Š” ๊ฒƒ ์žŠ์ง€ ๋งˆ์„ธ์š”).

๋งŒ์•ฝ ์—ฐ๊ฒฐ ๋ชจ๋ธ์ƒ์— ๊ฒ€์ฆ(validations), ๋˜๋ถ€๋ฆ„, ์ถ”๊ฐ€ ์†์„ฑ๋“ฑ์ด ํ•„์š”ํ•˜๋‹ค๋ฉด, has_many :through๋ฅผ ์‚ฌ์šฉํ•˜์…”์•ผ ํ•ฉ๋‹ˆ๋‹ค.

ํด๋ฆฌ๋ชจํ”ฝ(polymorphic: ๋‹ค์ค‘) ๊ด€๊ณ„

์•ฝ๊ฐ„์€ ์ง„์ผ๋ณดํ•œ ๊ด€๊ณ„๋กœ์จ, ํด๋ฆฌ๋ชจํ”ฝ ๊ด€๊ณ„ ๋ผ๋Š” ๊ฒƒ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ํด๋ฆฌ๋ชจํŽ™ ๊ด€๊ณ„๋ฅผ ์ด์šฉํ•˜๋ฉด, ํ•˜๋‚˜์˜ ๋ชจ๋ธ์ด ํ•˜๋‚˜ ๋˜๋Š” ์—ฌ๋Ÿฌ ๋ชจ๋ธ์— ์†ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ์šฐ๋ฆฌ๊ฐ€ ์‚ฌ์ง„(picture)์ด๋ผ๋Š” ๋ชจ๋ธ์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ์‚ฌ์ง„์ด๋ผ๋Š” ๋ชจ๋ธ์ด ์ง์›(employee) ๋ชจ๋ธ ๋˜๋Š” ์ƒ์‚ฐํ’ˆ(product) ๋ชจ๋ธ์— ์†ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜๋  ์ˆ˜ ์žˆ๊ฒ ์Šต๋‹ˆ๋‹ค.

class Picture < ActiveRecord::Base
belongs_to :imageable, :polymorphic => true
end

class Employee < ActiveRecord::Base
has_many :pictures, :as => :imageable
end

class Product < ActiveRecord::Base
has_many :pictures, :as => :imageable
end

๋‹น์‹ ์€ ํด๋ฆฌ๋ชจํ”ฝ belongs_to ์„ ์–ธ์„ ๊ทธ ์–ด๋–ค ๋‹ค๋ฅธ๋ชจ๋ธ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์„ค์ •ํ•œ ๊ฒƒ์œผ๋กœ ์ƒ๊ฐํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. +Employee+๋ชจ๋ธ์˜ ์‹ค์˜ˆ์—์„œ ๋‹น์‹ ์€ @employee.pictures ์ฒ˜๋Ÿผ ์‚ฌ์ง„์ง‘ํ•ฉ์„ ์ ‘๊ทผํ•˜์—ฌ ์ฝ์–ด๋“ค์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋‹จ์ˆœํžˆ, @product.pictures ๋ผ๊ณ  ๋ถˆ๋Ÿฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋งŒ์•ฝ Picture ๋ชจ๋ธ์˜ ์‹ค์˜ˆ๋ฅผ ํ•˜๋‚˜ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค๋ฉด, ์šฐ๋ฆฌ๋Š”[email protected]+ ํ˜ธ์ถœ์„ ํ†ตํ•ด์„œ ์ด๊ฒƒ์ด ์†ํ•œ ๋ถ€(parent)๋ฅผ ์ ‘๊ทผํ• ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์ด ์ž‘๋™ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š”, ์šฐ๋ฆฐ ์ด ํด๋ฆฌ๋ชจํ”ฝ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์„ ์–ธํ•˜๋Š” ์™ธ๋ถ€ ์—ด์‡  ํ–‰๊ณผ ์œ ํ˜• ํ–‰ ๋ชจ๋‘๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ ์–ธํ•˜์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.

class CreatePictures < ActiveRecord::Migration
def self.up
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
end

def self.down drop_table :pictures end

end

์ด ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์€ t.references ํ˜•์‹(ํผ)์„ ์ด์šฉํ•ด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋” ๊ฐ„๋žตํ™” ๋ ์ˆ˜ ์žˆ๊ฒ ์Šต๋‹ˆ๋‹ค.

class CreatePictures < ActiveRecord::Migration
def self.up
create_table :pictures do |t|
t.string :name
t.references :imageable, :polymorphic => true
t.timestamps
end
end

def self.down drop_table :pictures end

end

Polymorphic Association Diagram

์ž์ฒด ์—ฐ๊ฒฐ

๋ฐ์ดํ„ฐ ๋ชจ๋ธ์„ ์„ค๊ณ„ํ•  ๋•Œ์— ๋‹น์‹ ์€ ํ•œ ๋ชจ๋ธ์ด ๊ทธ ๋ชจ๋ธ ์ž์‹ ๊ณผ ์—ฐ๊ด€์ด ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ์ข…์ข… ๋ฐœ๊ฒฌํ•˜๊ฒŒ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด, ๋ชจ๋“  ์ง์›๋“ค์„ ํ•˜๋‚˜์˜ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ๋ชจ๋ธ๋กœ ์ €์žฅํ•˜๊ธธ ์›ํ•˜์ง€๋งŒ, ์ง์›๋“ค ์ค‘ ๊ด€๋ฆฌ์ž(manager)์™€ ํŒ€์›(subordinates)์˜ ๊ด€๊ณ„๋ฅผ ์ถ”์ ํ•˜๊ณ  ์‹ถ์–ดํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ์ƒํ™ฉ์€ ์ž์ฒด์—ฐ๊ฒฐ ๊ด€๊ณ„๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ชจ๋ธ๋ง ๋ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => โ€œEmployeeโ€,
:foreign_key => โ€œmanager_idโ€
belongs_to :manager, :class_name => โ€œEmployeeโ€
end

์ด ์„ค์ •์„ ์‚ฌ์šฉํ•  ๋•Œ์— ์šฐ๋ฆฌ๋Š”[email protected]+ ์™€ @employee.manager ๋ฅผ ์ ‘๊ทผํ•˜์—ฌ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํŒ, ๋ฌ˜์ˆ˜, ๊ทธ๋ฆฌ๊ณ  ๊ฒฝ๊ณ 

์—ฌ๊ธฐ์„œ ์šฐ๋ฆฌ๊ฐ€ ๋ ˆ์ผ์ฆˆ ์‘์šฉํ”„๋กœ๊ทธ๋žจ์—์„œ ํšจ๊ณผ์ ์œผ๋กœ ํ™œ์„ฑ ๋ ˆํฌ๋„๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ๋ช‡๊ฐ€์ง€ ์•Œ์•„์•ผ ํ•  ๊ฒƒ๋“ค์ด ์žˆ์Šต๋‹ˆ๋‹ค.

  • ์ผ€์‰ฌ(chach์ž„์‹œ์ €์žฅ) ์ œ์–ดํ•˜๊ธฐ
  • ์ด๋ฆ„ ์ถฉ๋Œ ํ”ผํ•˜๊ธฐ
  • ์Šคํ‚ค๋งˆ(schema) ๋งŒ๋“ค๊ธฐ
  • ๊ด€๋ จ ๋ฒ”์œ„ ์ œ์–ดํ•˜๊ธฐ

์ผ€์‰ฌ ์ œ์–ดํ•˜๊ธฐ

๊ด€๊ณ„์™€ ๊ด€๋ จ๋œ ๋ชจ๋“  ํ•จ์ˆ˜๋Š” ์ž„์‹œ ์ €์žฅ์„ ํ•˜๊ฒŒ๋˜๋Š”๋ฐ, ์ด ๋ง์€ ๊ฐ€์žฅ ์ตœ๊ทผ๋“ค์–ด ์ˆ˜ํ–‰๋œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์งˆ์˜๋ฅผ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ์–ตํ•œ๋‹ค๋Š” ๊ฒƒ์„ ๋งํ•ฉ๋‹ˆ๋‹ค. ์ด ์ž„์‹œ์ €์žฅ์€ ํ•จ์ˆ˜๋“ค ์‚ฌ์ด์—์„œ ์‹ฌ์ง€์–ด ๊ณต์œ ๋˜๊ธฐ๋„ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ ์˜ˆ๋ฅผ ๋ณด์‹œ์ฃ .

customer.orders # ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์ฃผ๋ฌธ๋“ค ์„ ์ฝ์Œ
customer.orders.size # ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค์˜ ์ผ€์‰ฌ ์‚ฌ์šฉ
customer.orders.empty? # ๋ฐ์ดํผ ๋ฒ ์ด์Šค์˜ ์ผ€์‰ฌ ์‚ฌ์šฉ

๋งŒ์•ฝ ์‘์‘ ํ”„๋กœ๊ทธ๋žจ์˜ ๋‹ค๋ฅธ ๋ถ€๋ถ„์—์„œ ๊ด€๋ จ๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์ •ํ•˜์—ฌ ๋ฉ”๋ชจ๋ฆฌ์ƒ์˜ ์ผ€์‰ฌ๋ฅผ ๊ฐฑ์‹ ํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด+true+ ๋ฅผ ๊ด€๊ณ„ํ˜ธ์ถœ์‹œ์— ์ธ์ž๋กœ ๋„˜๊ฒจ ์ฃผ์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

customer.orders # ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค์˜ ์ฃผ๋ฌธ๋“ค์„ ์ฝ์Œ
customer.orders.size # ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค์˜ ์ผ€์‰ฌ ์‚ฌ์šฉ
customer.orders(true).empty? # ์ผ€์‰ฌ๋ฅผ ๋ฌด์‹œํ•˜๊ณ  ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ์ฝ์Œ

์ด๋ฆ„ ์ถฉ๋Œ ํ”ผํ•˜๊ธฐ

๋‹น์‹ ์€ ๊ด€๊ณ„๋ฅผ ์ •์˜ํ•  ๋•Œ์— ์•„๋ฌด์ด๋ฆ„์ด๋‚˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์€ ์•„๋‹™๋‹ˆ๋‹ค. ๊ด€๊ณ„๋ฅผ ์ƒ์„ฑํ•  ๋•Œ์— ๊ด€๋ จ๋œ ๋ชจ๋ธ์— ๊ด€๊ณ„๋ช…๊ณผ ๋™์ผํ•œ ํ•จ์ˆ˜๊ฐ€ ์ƒ์„ฑ๋˜๊ธฐ ๋•Œ๋ฌธ์—+ActiveRecord::Base+ ์˜ ํ•จ์ˆ˜์™€ ๋™์ผํ•œ ์ด๋ฆ„์„ ๊ด€๊ณ„๋ช…์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ๋ฐ”๋žŒ์ง ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ, ๊ด€๊ณ„ ํ•จ์ˆ˜๊ฐ€ ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ ๊ธฐ์ดˆํ•จ์ˆ˜๋ฅผ ๋ฎ์–ด์จ๋ฒ„๋ฆฌ๊ฒŒ ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, attributes ๋˜๋Š” connection ์€ ๊ด€๊ณ„ ๋ช…์œผ๋กœ ๋ฐ”๋žŒ์ง ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์Šคํ‚ค๋งˆ ๊ฐฑ์‹ ํ•˜๊ธฐ

๊ด€๊ณ„๋Š” ๋Œ€๋‹จํžˆ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ ‡์ง€๋งŒ ์ด๊ฒƒ์ด ๋งˆ์ˆ ์ผ ์ˆ˜๋Š” ์—†์Šต๋‹ˆ๋‹ค. ์šฐ๋ฆฌ์—๊ฒŒ๋Š” ๊ด€๊ณ„์™€ ๋ฐ์ดํƒ€ ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ๊ฐ€ ๋ถ€ํ•ฉ ๋˜๋„๋ก ๊ด€๋ฆฌํ•  ์ฑ…์ž„์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์‹ค์žฌ๋กœ ์ด ๋ง์€ ์šฐ๋ฆฌ๊ฐ€ ๋งŒ๋“ค ๊ด€๊ณ„์˜ ์ข…๋ฅ˜์— ๋”ฐ๋ผ์„œ ๋‘๊ฐ€์ง€ ์˜๋ฏธ๋ฅผ ๊ฐ–์Šต๋‹ˆ๋‹ค. belongs_to ๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, ์™ธ๋ž˜ ์—ด์‡ ๋ฅผ ์ƒ์„ฑํ•ด์•ผ ํ•  ๊ฒƒ์ด๊ณ , has_and_belongs_to_many ์— ๋Œ€ํ•ด์„œ๋Š” ์˜ฌ๋ฐ”๋ฅธ ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์„ ์ƒ์„ฑํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

belongs_to ๊ด€๊ณ„๋ฅผ ์œ„ํ•œ ์™ธ๋ž˜ ์—ด์‡  ๋งŒ๋“ค๊ธฐ

belongs_to ๊ด€๊ณ„๋ฅผ ๋งŒ๋“ค๋•Œ์—, ๋‹น์‹ ์€ ์˜ฌ๋ฐ”๋ฅธ ์™ธ๋ž˜ํ‚ค๋ฅผ ๋งŒ๋“ค ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ๋‹ค์Œ ๋ชจ๋ธ์„ ์ƒ๊ฐํ•ด ๋ณด์ž.

class Order < ActiveRecord::Base
belongs_to :customer
end

์ด ์„ ์–ธ์€ ์˜ฌ๋ฐ”๋ฅธ ์™ธ๋ž˜ ์—ด์‡ ์˜ ์„ ์–ธ์„ ๋‹ค๋ฅธ ์ฃผ๋ฌธ ํ…Œ์ด๋ธ”์— ์ €์žฅํ•ด์•ผ ํ•œ๋‹ค.

class CreateOrders < ActiveRecord::Migration
def self.up
create_table :orders do |t|
t.datetime :order_date
t.string :order_number
t.integer :customer_id
end
end

def self.down drop_table :orders end

end

๋งŒ์•ฝ ๋‹น์‹ ์ด ๋ชจ๋ธ์„ ๋งŒ๋“  ํ•œ์ฐธ ํ›„์— ๊ด€๊ณ„๋ฅผ ์ƒ์„ฑํ–ˆ๋‹ค๋ฉด, ๋‹น์‹ ์€ ํ•„์š”ํ•œ ์™ธ๋ž˜ ์—ด์‡ ๋ฅผ ์ œ๊ณตํ•˜๊ณ ์ž belongs_to ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์„ ์ƒ์„ฑํ•˜๋Š” ๊ฒƒ์„ ๊ธฐ์–ตํ•ด์•ผ ํ•œ๋‹ค.
has_and_belongs_to_many ๊ด€๊ณ„๋ฅผ ์œ„ํ•œ ์—ฐ๊ฒฐํ…Œ์ด๋ธ” ์ƒ์„ฑํ•˜๊ธฐ

๋งŒ์•ฝ ์šฐ๋ฆฌ๊ฐ€+has_and_belongs_to_many+ ๊ด€๊ณ„๋ฅผ ์ƒ์„ฑํ•œ๋‹ค๋ฉด, ์šฐ๋ฆฌ๋Š” ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์„ ๋ช…ํ™•ํ•˜๊ฒŒ ์ƒ์„ฑํ•  ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. :join_table ์˜ต์…˜์„ ์‚ฌ์šฉํ•˜์—ฌ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์˜ ์ด๋ฆ„์„ ๋ช…ํ™•ํ•˜๊ฒŒ ๋ฐํžˆ์ง€ ์•Š๋Š” ์ด์ƒ์—๋Š”, ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ๋Š” ํด๋ž˜์Šค๋ช…์„ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ๋ฐฐ์—ดํ•œ ์ด๋ฆ„์„ ์‚ฌ์šฉํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๊ณ ๊ฐ(customer)๊ณผ ์ฃผ๋ฌธ(order) ๋ชจ๋ธ์‚ฌ์ด์˜ ์—ฐ๊ฒฐ์€ โ€œcustomers_ordersโ€ ๋ช…์„ ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์˜ ์ด๋ฆ„์œผ๋กœ ์‚ฌ์šฉํ•˜๊ฒŒ ๋ ํ…๋ฐ ๊ทธ ์ด์œ ๋Š” ๊ณ ๊ฐ์˜ ์˜๋ฌธ๋‹จ์–ด ์ฒซ๊ธ€์ž "c"๊ฐ€ ์ฃผ๋ฌธ์˜ ์˜๋ฌธ๋‹จ์–ด ์ฒซ๊ธ€์ž โ€œoโ€ ๋ณด๋‹ค ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ๋จผ์ €์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

๋ชจ๋ธ๋ช…๊ฐ„์˜ ์šฐ์„ ์ˆœ์šฐ๋ฅผ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ๊ฒฐ์ •ํ•  ๋•Œ์— ๋ฌธ์ž์—ด์„ ์œ„ํ•œ ๊ฐ์ฒด+String+ ์— ์ •์˜๋œ < ์—ฐ์‚ฐ์ž(operator)๊ฐ€ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ์ด ๋ง์€ ๋น„๊ต๋˜๋Š” ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋•Œ์—๋Š” ์งง์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊นŒ์ง€๋งŒ์„ ์„œ๋กœ ๋น„๊ตํ•˜๊ฒŒ ๋˜๋Š”๋ฐ, ์ด๋ž˜๊ณ  ๊ฐ™์„ ๊ฒฝ์šฐ์—๋Š”, ๊ธธ์ด๊ฐ€ ๊ธด ๋ฌธ์ž์—ด์ด ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ๋” ๋’ค์— ๋†“์ด๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด๋‘ ๋ชจ๋ธ โ€œpaper_boxesโ€ ์™€ โ€œpapersโ€ ๋ฅผ ์—ฐ๊ฒฐํ•˜๋Š” ํ…Œ์ด๋ธ”์˜ ์ƒ์„ฑ์‹œ๋ฅผ ์ƒ๊ฐํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ์งง์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊นŒ์ง€๋งŒ์„ ๋น„๊ตํ•จ์œผ๋กœ ๋‚ด๋ถ€์ ์œผ๋กœ"paper_โ€ ์™€ โ€œpapersโ€ ๋ฅผ ๋น„๊ตํ•˜๊ฒŒ ๋˜๊ณ , ๋ฌธ์žโ€™_โ€™ ๋ณด๋‹ค โ€˜sโ€™ ๊ฐ€ ๋” ์•ž์„œ ๋ฏ€๋กœ, ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ” ์ด๋ฆ„์€ โ€œpapers_paper_boxesโ€ ๋กœ ์ƒ์„ฑ๋˜์ง€ ์•Š๊ณ , ๋Œ€์‹  โ€œpapers_paper_boxesโ€ ์œผ๋กœ ์ƒ์„ฑ๋ฉ๋‹ˆ๋‹ค.

์ด๋ฆ„์ด ๋ฌด์—‡์ด๋˜ ๊ฐ„์—, ์šฐ๋ฆฌ๋Š” ์˜ฌ๋ฐ”๋ฅธ ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์„ ํ†ตํ•ด ์—ฐ๊ฒฐ ํ…Œ์ด๋ธ”์„ ์†์ˆ˜ ์ƒ์„ฑํ•ด์•ผ๋งŒ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด ๋‹ค์Œ ๊ด€๊ณ„์˜ˆ์ œ๋“ค๊ณผ ๊ฐ™์ด ๋ง์ž…๋‹ˆ๋‹ค.

class Assembly < ActiveRecord::Base
has_and_belongs_to_many :parts
end

class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end

์ด ๋ชจ๋ธ๋“ค์€ assemblies_parts ํ…Œ์ด๋ธ”์˜ ์ƒ์„ฑ์„ ์œ„ํ•ด์„œ ๋งˆ์ด๊ทธ๋ ˆ์ด์…˜์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์ด ํ…Œ์ด๋ธ”์€ ์ฃผ์—ด์‡  ์—†์ด ์ƒ์„ฑ๋˜์–ด์•ผ๋งŒ ํ•ฉ๋‹ˆ๋‹ค.

class CreateAssemblyPartJoinTable < ActiveRecord::Migration
def self.up
create_table :assemblies_parts, :id => false do |t|
t.integer :assembly_id
t.integer :part_id
end
end

def self.down drop_table :assemblies_parts end

end

์šฐ๋ฆฌ๋Š”+:id => false+ ๋ฅผ +create_table+๋ฅผ ์ธ์ž๋กœ ๋„˜๊ฒผ์Šต๋‹ˆ๋‹ค. ๊ทธ ์ด์œ ๋Š” ๊ทธ ํ…Œ์ด๋ธ”์ด ๋ชจ๋ธ์„ ํ‘œํ˜„ํ•˜๊ณ  ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์ด๋ฉฐ ์ œ๋Œ€๋กœ ์ž‘๋™ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๊ด€๊ณ„๋Š” ๊ทธ๋Ÿฌํ•œ ์ธ์ž๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๋‹น์‹ ์ด+has_and_belongs_to_many+๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ์— ๊นจ์ง„ ๋ชจ๋ธ ์•„์ด๋””๋‚˜ ์•„์ด๋”” ์ถฉ๋Œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ์™€ ๊ฐ™์€ ์ด์ƒํ•œ ์ˆ˜ํ–‰๊ฒฐ๊ณผ๋ฅผ ๋ฐœ๊ฒฌํ•œ๋‹ค๋ฉด, ์•„๋งˆ๋„ ์ด์™€ ๊ฐ™์ด ์ธ์ž๋ฅผ ๋„˜๊ธฐ์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๊ด€๊ณ„ ๋ฒ”์œ„ ์ œ์–ดํ•˜๊ธฐ

๊ธฐ๋ณธ์œผ๋กœ ๊ด€๊ณ„๋Š” ํ˜„ ๋ชจ๋ธ์˜ ๋ฒ”์œ„๋‚ด์—์„œ ๊ฐ์ฒด์˜ ์˜ˆ๋“ค์„ ์ฐพ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ์šฐ๋ฆฌ๊ฐ€ ํ™œ์„ฑ ๋ ˆ์ฝ”๋“œ ๋ชจ๋ธ์„ ์„ ์–ธํ•  ๋•Œ์— ์ค‘์š”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์Œ ์˜ˆ๋ฅผ ๋ณด์‹œ์ฃ .

module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end

class Account < ActiveRecord::Base belongs_to :supplier end end

end

์ด ์˜ˆ์ œ ์ฝ”๋“œ๋Š” ๋ฌธ์ œ ์—†์ด ์ž‘๋™ ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์™œ๋ƒํ•˜๋ฉด+Supplier+ ์™€ Account ๊ฐ์ฒด๊ฐ€ ๋™์ผํ•œ ๋ฒ”์œ„, ์ฆ‰, ๋ชจ๋“ˆ๋‚ด์—์„œ ์ •์˜๊ฐ€ ๋๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋ฐ˜๋Œ€๋กœ, ๋‹ค์Œ์˜ ์˜ˆ์—์„œ๋Š” Supplier ์™€ Account ์ œ๋Œ€๋กœ ์ž‘๋™ํ•˜์ง€ ์•Š์„ํ…๋ฐ ๊ทธ ์ด์œ ๋Š” ์ด๋“ค์ด ๋‹ค๋ฅธ ๋ฒ”์œ„์—์„œ ์ •์˜๋๊ธฐ ๋•Œ๋ฌธ์ด์ฃ .

module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end
end

module Billing class Account < ActiveRecord::Base belongs_to :supplier end end

end

๋‹ค๋ฅธ ์ด๋ฆ„๊ณต๊ฐ„(namespace)์— ์ •์˜๋œ ๋ชจ๋ธ๋“ค ์‚ฌ์ด๋ฅผ ๊ด€๊ณ„ ๋งบ๊ณ ์ž ํ•  ๊ฒฝ์šฐ, ์šฐ๋ฆฌ๋Š” ์™„์ „ํ•œ ๊ฐ์ฒด ๋ช…์„ ๊ด€๊ณ„์ •์˜์— ๋ช…์‹œํ•ด์•ผ ๋ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ์„ ๋ณด์‹œ์ฃ .

module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account,
:class_name => โ€œMyApplication::Billing::Accountโ€
end
end

module Billing class Account < ActiveRecord::Base belongs_to :supplier, :class_name => โ€œMyApplication::Business::Supplierโ€ end end

end

์ž์„ธํ•œ ๊ด€๊ณ„ ์ฐธ๊ณ ์ž๋ฃŒ

The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
๋‹ค์Œ ์ ˆ์€ ๊ฐ ๊ด€๊ณ„์˜ ์œ ํ˜•๋ณ„ ์ƒ์„ธ์ž๋ฃŒ๋ฅผ ๋‹ด๊ณ  ์žˆ์Šต๋Š”๋ฐ, ์ƒ์„ฑ๋˜๋Š” ๊ฐ์ฒด ํ•จ์ˆ˜๋“ค๊ณผ ์ด๋“ค์˜ ์˜ต์…˜๋“ค์„ ๋ณด์‹œ๊ฒŒ ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

belongs_to ๊ด€๊ณ„ ์ฐธ๊ณ ์ž๋ฃŒ

belongs_to ๊ด€๊ณ„๋Š” ๋‹ค๋ฅธ ๋ชจ๋ธ๊ณผ์˜ 1:1 ๊ด€๊ณ„๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์šฉ์–ด๋กœ๋Š” ์ด ๊ด€๊ณ„๊ฐ์ฒด๊ฐ€ ์™ธ๋ž˜ ์—ด์‡ ๋ฅผ ๊ฐ–๊ฒŒ๋œ๋‹ค๊ณ  ๋งํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ด€๋ จ๋œ ๋‹ค๋ฅธ ๊ฐ์ฒด๊ฐ€ ์™ธ๋ž˜ ์—ด์‡ ๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค๋ฉด, ์šฐ๋ฆฌ๋Š”+has_one+ ๊ด€๊ณ„๋ฅผ ๋Œ€์‹  ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

belongs_to ์— ์˜ํ•ด์„œ ์ถ”๊ฐ€๋˜๋Š” ํ•จ์ˆ˜๋“ค

belongs_to ๊ด€๊ณ„๋ฅผ ์„ ์–ธํ•  ๋•Œ์—, ์„ ์–ธํ•˜๋Š” ํด๋ž˜์Šค๋Š” ์ž๋™์œผ๋กœ ๋‹ค์Œ์˜ ๋„ค๊ฐ€์ง€ ํ•จ์ˆ˜๋“ค์„ ๊ฐ€์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

  • association(force_reload = false)
  • association=(associate)
  • build_association(attributes = {})
  • create_association(attributes = {})

์ด ๋ชจ๋“  ํ•จ์ˆ˜๋“ค์—์„œassociation๋Š”+belongs_to+ ๊ด€๊ณ„์— ์ •์˜๋œ ๋ชจ๋ธ๋ช…์œผ๋กœ ๋ฐ”๋€Œ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ์˜ ์˜ˆ๋ฅผ ๋ณด์‹œ์ฃ .

class Order < ActiveRecord::Base
belongs_to :customer
end

๊ฐ ๋ชจ๋ธ์˜ ์‹ค์˜ˆ๋Š” ์ด๋Ÿฌํ•œ ํ•จ์ˆ˜๋“ค์„ ๊ฐ–๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ์ฆ‰, ์ฃผ๋ฌธ(order)์˜ ์‹ค์˜ˆ(instance)๋Š” ๊ด€๋ จ๋œ ๋‹ค์Œ์˜ ํ•จ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

customer
customer=
build_customer
create_customer

association(force_reload = false)
association ๋ฉ”์„œ๋“œ๋Š” ๊ด€๋ จ๋œ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š”๋ฐ, ๋งŒ์•ฝ, ๊ด€๋ จ๋œ ๊ฐ์ฒด๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด nil ์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

@customer = @order.customer

๋งŒ์•ฝ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋กœ๋ถ€ํ„ฐ ๊ด€๋ จ๊ฐ์ฒด์„ ๋ฒŒ์จ ์ฝ์—ˆ๋‹ค๋ฉด ์ด ๊ฒƒ์€ ์ž„์‹œ์ €์žฅ์†Œ(์ผ€์‰ฌ)์˜ ๊ฒƒ์ด ๋ฐ˜ํ™˜๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์บ์‰ฌ์˜ ๊ฒƒ์„ ์‚ฌ์šฉํ•˜๋Š” ์ด ๋ฐฉ๋ฒ•์„ ๋ฌด์‹œํ•˜๊ณ  ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค์˜ ๊ฒƒ์„ ์ฝ๊ธฐ๋ฅผ ์›ํ•œ๋‹ค๋ฉด, force_reload ์— ํ•ด๋‹นํ•˜๋Š” ์ธ์ž๊ฐ’์„ true ๋กœ ๋„˜๊ธฐ์…”์•ผ ํ•ฉ๋‹ˆ๋‹ค.

association=(associate)
association= ๋ฉ”์„œ๋“œ๋Š” ๊ด€๋ จ๋œ ๊ฐ์ฒด๋ฅผ ์„ค์ •ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ๋‚ด๋ถ€์ ์œผ๋กœ ์ด๊ฒƒ์€ ๊ด€๋ จ ๊ฐ์ฒด์˜ (๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค์˜) ์ฃผ ์—ด์‡ ๊ฐ’์„ ๊บผ๋‚ด์™€ (๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜) ์™ธ๋ถ€ ์—ด์‡ ๋กœ ๋ณต์‚ฌํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

@order.customer = @customer

build_association(attributes = {})

The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this objectโ€™s foreign key will be set, but the associated object will not yet be saved.

@customer = @order.build_customer(:customer_number => 123,
:customer_name => โ€œJohn Doeโ€)

create_association(attributes = {})

The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this objectโ€™s foreign key will be set. In addition, the associated object will be saved (assuming that it passes any validations).

@customer = @order.create_customer(:customer_number => 123,
:customer_name => โ€œJohn Doeโ€)

Options for belongs_to

In many situations, you can use the default behavior of belongs_to without any customization. But despite Railsโ€™ emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a belongs_to association. For example, an association with several options might look like this:

class Order < ActiveRecord::Base
belongs_to :customer, :counter_cache => true,
:conditions => โ€œactive = 1โ€
end

The belongs_to association supports these options:

  • :autosave
  • :class_name
  • :conditions
  • :counter_cache
  • :dependent
  • :foreign_key
  • :include
  • :polymorphic
  • :readonly
  • :select
  • :touch
  • :validate
:autosave

If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

:class_name

If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is Patron, youโ€™d set things up this way:

class Order < ActiveRecord::Base
belongs_to :customer, :class_name => โ€œPatronโ€
end

:conditions

The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL WHERE clause).

class Order < ActiveRecord::Base
belongs_to :customer, :conditions => โ€œactive = 1โ€
end

:counter_cache

The :counter_cache option can be used to make finding the number of belonging objects more efficient. Consider these models:

class Order < ActiveRecord::Base
belongs_to :customer
end
class Customer < ActiveRecord::Base
has_many :orders
end

With these declarations, asking for the value of @customer.orders.size requires making a call to the database to perform a COUNT query. To avoid this call, you can add a counter cache to the belonging model:

class Order < ActiveRecord::Base
belongs_to :customer, :counter_cache => true
end
class Customer < ActiveRecord::Base
has_many :orders
end

With this declaration, Rails will keep the cache value up to date, and then return that value in response to the size method.

Although the :counter_cache option is specified on the model that includes the belongs_to declaration, the actual column must be added to the associated model. In the case above, you would need to add a column named orders_count to the Customer model. You can override the default column name if you need to:

class Order < ActiveRecord::Base
belongs_to :customer, :counter_cache => :count_of_orders
end
class Customer < ActiveRecord::Base
has_many :orders
end

Counter cache columns are added to the containing modelโ€™s list of read-only attributes through attr_readonly.

:dependent

If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method.

WARNING: You should not specify this option on a belongs_to association that is connected with a has_many association on the other class. Doing so can lead to orphaned records in your database.

:foreign_key

By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:

class Order < ActiveRecord::Base
belongs_to :customer, :class_name => โ€œPatronโ€,
:foreign_key => โ€œpatron_idโ€
end

TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.

:include

You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:

class LineItem < ActiveRecord::Base
belongs_to :order
end

class Order < ActiveRecord::Base
belongs_to :customer
has_many :line_items
end

class Customer < ActiveRecord::Base
has_many :orders
end

If you frequently retrieve customers directly from line items (@line_item.order.customer), then you can make your code somewhat more efficient by including customers in the association from line items to orders:

class LineItem < ActiveRecord::Base
belongs_to :order, :include => :customer
end

class Order < ActiveRecord::Base
belongs_to :customer
has_many :line_items
end

class Customer < ActiveRecord::Base
has_many :orders
end

NOTE: Thereโ€™s no need to use :include for immediate associations โ€“ that is, if you have Order belongs_to :customer, then the customer is eager-loaded automatically when itโ€™s needed.

:polymorphic

Passing true to the :polymorphic option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.

:readonly

If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.

:select

The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.

TIP: If you set the :select option on a belongs_to association, you should also set the foreign_key option to guarantee the correct results.

:touch

If you set the :touch option to :true, then the updated_at or updated_on timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:

class Order < ActiveRecord::Base
belongs_to :customer, :touch => true
end

class Customer < ActiveRecord::Base
has_many :orders
end

In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:

class Order < ActiveRecord::Base
belongs_to :customer, :touch => :orders_updated_at
end

:validate

If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.

How To Know Whether Thereโ€™s an Associated Object?

To know whether thereโ€™s and associated object just check association.nil?:

if @order.customer.nil?
@msg = โ€œNo customer found for this orderโ€
end

When are Objects Saved?

Assigning an object to a belongs_to association does not automatically save the object. It does not save the associated object either.

has_one Association Reference

The has_one association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use belongs_to instead.

Methods Added by has_one

When you declare a has_one association, the declaring class automatically gains four methods related to the association:

  • association(force_reload = false)
  • association=(associate)
  • build_association(attributes = {})
  • create_association(attributes = {})

In all of these methods, association is replaced with the symbol passed as the first argument to has_one. For example, given the declaration:

class Supplier < ActiveRecord::Base
has_one :account
end

Each instance of the Supplier model will have these methods:

account
account=
build_account
create_account

NOTE: When initializing a new has_one or belongs_to association you must use the build_ prefix to build the association, rather than the association.build method that would be used for has_many or has_and_belongs_to_many associations. To create one, use the create_ prefix.

association(force_reload = false)

The association method returns the associated object, if any. If no associated object is found, it returns nil.

@account = @supplier.account

If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass true as the force_reload argument.

association=(associate)

The association= method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate objectโ€™s foreign key to the same value.

@supplier.account = @account

build_association(attributes = {})

The build_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will not yet be saved.

@account = @supplier.build_account(:terms => โ€œNet 30โ€)

create_association(attributes = {})

The create_association method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object will be saved (assuming that it passes any validations).

@account = @supplier.create_account(:terms => โ€œNet 30โ€)

Options for has_one

In many situations, you can use the default behavior of has_one without any customization. But despite Railsโ€™ emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_one association. For example, an association with several options might look like this:

class Supplier < ActiveRecord::Base
has_one :account, :class_name => โ€œBillingโ€, :dependent => :nullify
end

The has_one association supports these options:

  • :as
  • :autosave
  • :class_name
  • :conditions
  • :dependent
  • :foreign_key
  • :include
  • :order
  • :primary_key
  • :readonly
  • :select
  • :source
  • :source_type
  • :through
  • :validate
:as

Setting the :as option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.

:autosave

If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

:class_name

If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, youโ€™d set things up this way:

class Supplier < ActiveRecord::Base
has_one :account, :class_name => โ€œBillingโ€
end

:conditions

The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL WHERE clause).

class Supplier < ActiveRecord::Base
has_one :account, :conditions => โ€œconfirmed = 1โ€
end

:dependent

If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated object to delete that object. If you set the :dependent option to :delete, then deleting this object will delete the associated object without calling its destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the association object to NULL.

:foreign_key

By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:

class Supplier < ActiveRecord::Base
has_one :account, :foreign_key => โ€œsupp_idโ€
end

TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.

:include

You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:

class Supplier < ActiveRecord::Base
has_one :account
end

class Account < ActiveRecord::Base
belongs_to :supplier
belongs_to :representative
end

class Representative < ActiveRecord::Base
has_many :accounts
end

If you frequently retrieve representatives directly from suppliers (@supplier.account.representative), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:

class Supplier < ActiveRecord::Base
has_one :account, :include => :representative
end

class Account < ActiveRecord::Base
belongs_to :supplier
belongs_to :representative
end

class Representative < ActiveRecord::Base
has_many :accounts
end

:order

The :order option dictates the order in which associated objects will be received (in the syntax used by an SQL ORDER BY clause). Because a has_one association will only retrieve a single associated object, this option should not be needed.

:primary_key

By convention, Rails guesses that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.

:readonly

If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.

:select

The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.

:source

The :source option specifies the source association name for a has_one :through association.

:source_type

The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association.

:through

The :through option specifies a join model through which to perform the query. has_one :through associations were discussed in detail earlier in this guide.

:validate

If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.

How To Know Whether Thereโ€™s an Associated Object?

To know whether thereโ€™s and associated object just check association.nil?:

if @supplier.account.nil?
@msg = โ€œNo account found for this supplierโ€
end

When are Objects Saved?

When you assign an object to a has_one association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.

If either of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.

If the parent object (the one declaring the has_one association) is unsaved (that is, new_record? returns true) then the child objects are not saved. They will automatically when the parent object is saved.

If you want to assign an object to a has_one association without saving the object, use the association.build method.

has_many Association Reference

The has_many association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.

Methods Added by has_many

When you declare a has_many association, the declaring class automatically gains 13 methods related to the association:

  • collection(force_reload = false)
  • collection<<(object, โ€ฆ)
  • collection.delete(object, โ€ฆ)
  • collection=objects
  • collection_singular_ids
  • collection_singular_ids=ids
  • collection.clear
  • collection.empty?
  • collection.size
  • collection.find(โ€ฆ)
  • collection.where(โ€ฆ)
  • collection.exists?(โ€ฆ)
  • collection.build(attributes = {}, โ€ฆ)
  • collection.create(attributes = {})

In all of these methods, collection is replaced with the symbol passed as the first argument to has_many, and collection_singular is replaced with the singularized version of that symbol.. For example, given the declaration:

class Customer < ActiveRecord::Base
has_many :orders
end

Each instance of the customer model will have these methods:

orders(force_reload = false)
orders<<(object, โ€ฆ)
orders.delete(object, โ€ฆ)
orders=objects
order_ids
order_ids=ids
orders.clear
orders.empty?
orders.size
orders.find(โ€ฆ)
orders.where(โ€ฆ)
orders.exists?(โ€ฆ)
orders.build(attributes = {}, โ€ฆ)
orders.create(attributes = {})

collection(force_reload = false)

The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.

@orders = @customer.orders

collection<<(object, โ€ฆ)

The collection<< method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.

@customer.orders << @order1

collection.delete(object, โ€ฆ)

The collection.delete method removes one or more objects from the collection by setting their foreign keys to NULL.

customer.orders.delete(order1)

WARNING: Additionally, objects will be destroyed if theyโ€™re associated with :dependent => :destroy, and deleted if theyโ€™re associated with :dependent => :delete_all.

collection=objects

The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.

collection_singular_ids

The collection_singular_ids method returns an array of the ids of the objects in the collection.

@order_ids = @customer.order_ids

collection_singular_ids=ids

The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.

collection.clear

The collection.clear method removes every object from the collection. This destroys the associated objects if they are associated with :dependent => :destroy, deletes them directly from the database if :dependent => :delete_all, and otherwise sets their foreign keys to NULL.

collection.empty?

The collection.empty? method returns true if the collection does not contain any associated objects.

<% if @customer.orders.empty? >
No Orders Found
<
end %>

collection.size

The collection.size method returns the number of objects in the collection.

@order_count = @customer.orders.size

collection.find(โ€ฆ)

The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find.

@open_orders = @customer.orders.all(:conditions => โ€œopen = 1โ€)

NOTE: Starting Rails 3, supplying options to ActiveRecord::Base.find method is discouraged. Use collection.where instead when you need to pass conditions.

collection.where(โ€ฆ)

The collection.where method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.

@open_orders = @customer.orders.where(:open => true) # No query yet
@open_order = @open_orders.first # Now the database will be queried

collection.exists?(โ€ฆ)

The collection.exists? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.

collection.build(attributes = {}, โ€ฆ)

The collection.build method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will not yet be saved.

@order = @customer.orders.build(:order_date => Time.now,
:order_number => โ€œA12345โ€)

collection.create(attributes = {})

The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object will be saved (assuming that it passes any validations).

@order = @customer.orders.create(:order_date => Time.now,
:order_number => โ€œA12345โ€)

Options for has_many

In many situations, you can use the default behavior for has_many without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_many association. For example, an association with several options might look like this:

class Customer < ActiveRecord::Base
has_many :orders, :dependent => :delete_all, :validate => :false
end

The has_many association supports these options:

  • :as
  • :autosave
  • :class_name
  • :conditions
  • :counter_sql
  • :dependent
  • :extend
  • :finder_sql
  • :foreign_key
  • :group
  • :include
  • :limit
  • :offset
  • :order
  • :primary_key
  • :readonly
  • :select
  • :source
  • :source_type
  • :through
  • :uniq
  • :validate
:as

Setting the :as option indicates that this is a polymorphic association, as discussed earlier in this guide.

:autosave

If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

:class_name

If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is Transaction, youโ€™d set things up this way:

class Customer < ActiveRecord::Base
has_many :orders, :class_name => โ€œTransactionโ€
end

:conditions

The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL WHERE clause).

class Customer < ActiveRecord::Base
has_many :confirmed_orders, :class_name => โ€œOrderโ€,
:conditions => โ€œconfirmed = 1โ€
end

You can also set conditions via a hash:

class Customer < ActiveRecord::Base
has_many :confirmed_orders, :class_name => โ€œOrderโ€,
:conditions => { :confirmed => true }
end

If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @customer.confirmed_orders.create or @customer.confirmed_orders.build will create orders where the confirmed column has the value true.

If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes:

class Customer < ActiveRecord::Base
has_many :latest_orders, :class_name => โ€œOrderโ€,
:conditions => โ€˜orders.created_at > #{10.hours.ago.to_s(:db).inspect}โ€™
end

Be sure to use single quotes.

:counter_sql

Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.

NOTE: If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT FROM for the SELECT โ€ฆ FROM clause of your :finder_sql statement.

:dependent

If you set the :dependent option to :destroy, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the :dependent option to :delete_all, then deleting this object will delete the associated objects without calling their destroy method. If you set the :dependent option to :nullify, then deleting this object will set the foreign key in the associated objects to NULL.

NOTE: This option is ignored when you use the :through option on the association.

:extend

The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.

:finder_sql

Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.

:foreign_key

By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:

class Customer < ActiveRecord::Base
has_many :orders, :foreign_key => โ€œcust_idโ€
end

TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.

:group

The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.

class Customer < ActiveRecord::Base
has_many :line_items, :through => :orders, :group => โ€œorders.idโ€
end

:include

You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:

class Customer < ActiveRecord::Base
has_many :orders
end

class Order < ActiveRecord::Base
belongs_to :customer
has_many :line_items
end

class LineItem < ActiveRecord::Base
belongs_to :order
end

If you frequently retrieve line items directly from customers (@customer.orders.line_items), then you can make your code somewhat more efficient by including line items in the association from customers to orders:

class Customer < ActiveRecord::Base
has_many :orders, :include => :line_items
end

class Order < ActiveRecord::Base
belongs_to :customer
has_many :line_items
end

class LineItem < ActiveRecord::Base
belongs_to :order
end

:limit

The :limit option lets you restrict the total number of objects that will be fetched through an association.

class Customer < ActiveRecord::Base
has_many :recent_orders, :class_name => โ€œOrderโ€,
:order => โ€œorder_date DESCโ€, :limit => 100
end

:offset

The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset => 11, it will skip the first 11 records.

:order

The :order option dictates the order in which associated objects will be received (in the syntax used by an SQL ORDER BY clause).

class Customer < ActiveRecord::Base
has_many :orders, :order => โ€œdate_confirmed DESCโ€
end

:primary_key

By convention, Rails guesses that the column used to hold the primary key of the association is id. You can override this and explicitly specify the primary key with the :primary_key option.

:readonly

If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.

:select

The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.

WARNING: If you specify your own :select, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.

:source

The :source option specifies the source association name for a has_many :through association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.

:source_type

The :source_type option specifies the source association type for a has_many :through association that proceeds through a polymorphic association.

:through

The :through option specifies a join model through which to perform the query. has_many :through associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.

:uniq

Set the :uniq option to true to keep the collection free of duplicates. This is mostly useful together with the :through option.

class Person < ActiveRecord::Base
has_many :readings
has_many :posts, :through => :readings
end

person = Person.create(:name => โ€˜johnโ€™)
post = Post.create(:name => โ€˜a1โ€™)
person.posts << post
person.posts << post
person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]

In the above case there are two readings and person.posts brings out both of them even though these records are pointing to the same post.

Now letโ€™s set :uniq to true:

class Person
has_many :readings
has_many :posts, :through => :readings, :uniq => true
end

person = Person.create(:name => โ€˜hondaโ€™)
post = Post.create(:name => โ€˜a1โ€™)
person.posts << post
person.posts << post
person.posts.inspect # => [#<Post id: 7, name: "a1">]
Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]

In the above case there are still two readings. However person.posts shows only one post because the collection loads only unique records.

:validate

If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.

When are Objects Saved?

When you assign an object to a has_many association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.

If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.

If the parent object (the one declaring the has_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.

If you want to assign an object to a has_many association without saving the object, use the collection.build method.

has_and_belongs_to_many Association Reference

The has_and_belongs_to_many association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.

Methods Added by has_and_belongs_to_many

When you declare a has_and_belongs_to_many association, the declaring class automatically gains 13 methods related to the association:

  • collection(force_reload = false)
  • collection<<(object, โ€ฆ)
  • collection.delete(object, โ€ฆ)
  • collection=objects
  • collection_singular_ids
  • collection_singular_ids=ids
  • collection.clear
  • collection.empty?
  • collection.size
  • collection.find(โ€ฆ)
  • collection.where(โ€ฆ)
  • collection.exists?(โ€ฆ)
  • collection.build(attributes = {})
  • collection.create(attributes = {})

In all of these methods, collection is replaced with the symbol passed as the first argument to has_and_belongs_to_many, and collection_singular is replaced with the singularized version of that symbol. For example, given the declaration:

class Part < ActiveRecord::Base
has_and_belongs_to_many :assemblies
end

Each instance of the part model will have these methods:

assemblies(force_reload = false)
assemblies<<(object, โ€ฆ)
assemblies.delete(object, โ€ฆ)
assemblies=objects
assembly_ids
assembly_ids=ids
assemblies.clear
assemblies.empty?
assemblies.size
assemblies.find(โ€ฆ)
assemblies.where(โ€ฆ)
assemblies.exists?(โ€ฆ)
assemblies.build(attributes = {}, โ€ฆ)
assemblies.create(attributes = {})

Additional Column Methods

If the join table for a has_and_belongs_to_many association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.

WARNING: The use of extra attributes on the join table in a has_and_belongs_to_many association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a has_many :through association instead of has_and_belongs_to_many.

collection(force_reload = false)

The collection method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.

@assemblies = @part.assemblies

collection<<(object, โ€ฆ)

The collection<< method adds one or more objects to the collection by creating records in the join table.

@part.assemblies << @assembly1

NOTE: This method is aliased as collection.concat and collection.push.

collection.delete(object, โ€ฆ)

The collection.delete method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.

part.assemblies.delete(assembly1)

collection=objects

The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.

collection_singular_ids

The collection_singular_ids method returns an array of the ids of the objects in the collection.

@assembly_ids = @part.assembly_ids

collection_singular_ids=ids

The collection_singular_ids= method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.

collection.clear

The collection.clear method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.

collection.empty?

The collection.empty? method returns true if the collection does not contain any associated objects.

<% if @part.assemblies.empty? >
This part is not used in any assemblies
<
end %>

collection.size

The collection.size method returns the number of objects in the collection.

@assembly_count = @part.assemblies.size

collection.find(โ€ฆ)

The collection.find method finds objects within the collection. It uses the same syntax and options as ActiveRecord::Base.find. It also adds the additional condition that the object must be in the collection.

@new_assemblies = @part.assemblies.all(
:conditions => [โ€œcreated_at > ?โ€, 2.days.ago])

NOTE: Starting Rails 3, supplying options to ActiveRecord::Base.find method is discouraged. Use collection.where instead when you need to pass conditions.

collection.where(โ€ฆ)

The collection.where method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.

@new_assemblies = @part.assemblies.where(โ€œcreated_at > ?โ€, 2.days.ago)

collection.exists?(โ€ฆ)

The collection.exists? method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as ActiveRecord::Base.exists?.

collection.build(attributes = {})

The collection.build method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will not yet be saved.

@assembly = @part.assemblies.build(
{:assembly_name => โ€œTransmission housingโ€})

collection.create(attributes = {})

The collection.create method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and the associated object will be saved (assuming that it passes any validations).

@assembly = @part.assemblies.create(
{:assembly_name => โ€œTransmission housingโ€})

Options for has_and_belongs_to_many

In many situations, you can use the default behavior for has_and_belongs_to_many without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a has_and_belongs_to_many association. For example, an association with several options might look like this:

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies, :uniq => true,
:read_only => true
end

The has_and_belongs_to_many association supports these options:

  • :association_foreign_key
  • :autosave
  • :class_name
  • :conditions
  • :counter_sql
  • :delete_sql
  • :extend
  • :finder_sql
  • :foreign_key
  • :group
  • :include
  • :insert_sql
  • :join_table
  • :limit
  • :offset
  • :order
  • :readonly
  • :select
  • :uniq
  • :validate
:association_foreign_key

By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix _id added. The :association_foreign_key option lets you set the name of the foreign key directly:

TIP: The :foreign_key and :association_foreign_key options are useful when setting up a many-to-many self-join. For example:

class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :class_name => โ€œUserโ€,
:foreign_key => โ€œthis_user_idโ€,
:association_foreign_key => โ€œother_user_idโ€
end

:autosave

If you set the :autosave option to true, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.

:class_name

If the name of the other model cannot be derived from the association name, you can use the :class_name option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is Gadget, youโ€™d set things up this way:

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies, :class_name => โ€œGadgetโ€
end

:conditions

The :conditions option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL WHERE clause).

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies,
:conditions => โ€œfactory = โ€˜Seattleโ€™โ€
end

You can also set conditions via a hash:

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies,
:conditions => { :factory => โ€˜Seattleโ€™ }
end

If you use a hash-style :conditions option, then record creation via this association will be automatically scoped using the hash. In this case, using @parts.assemblies.create or @parts.assemblies.build will create orders where the factory column has the value โ€œSeattleโ€.

:counter_sql

Normally Rails automatically generates the proper SQL to count the association members. With the :counter_sql option, you can specify a complete SQL statement to count them yourself.

NOTE: If you specify :finder_sql but not :counter_sql, then the counter SQL will be generated by substituting SELECT COUNT FROM for the SELECT โ€ฆ FROM clause of your :finder_sql statement.

:delete_sql

Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the :delete_sql option, you can specify a complete SQL statement to delete them yourself.

:extend

The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.

:finder_sql

Normally Rails automatically generates the proper SQL to fetch the association members. With the :finder_sql option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.

:foreign_key

By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:

class User < ActiveRecord::Base
has_and_belongs_to_many :friends, :class_name => โ€œUserโ€,
:foreign_key => โ€œthis_user_idโ€,
:association_foreign_key => โ€œother_user_idโ€
end

:group

The :group option supplies an attribute name to group the result set by, using a GROUP BY clause in the finder SQL.

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies, :group => โ€œfactoryโ€
end

:include

You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.

:insert_sql

Normally Rails automatically generates the proper SQL to create links between the associated classes. With the :insert_sql option, you can specify a complete SQL statement to insert them yourself.

:join_table

If the default name of the join table, based on lexical ordering, is not what you want, you can use the :join_table option to override the default.

:limit

The :limit option lets you restrict the total number of objects that will be fetched through an association.

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies, :order => โ€œcreated_at DESCโ€,
:limit => 50
end

:offset

The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset => 11, it will skip the first 11 records.

:order

The :order option dictates the order in which associated objects will be received (in the syntax used by an SQL ORDER BY clause).

class Parts < ActiveRecord::Base
has_and_belongs_to_many :assemblies, :order => โ€œassembly_name ASCโ€
end

:readonly

If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.

:select

The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.

:uniq

Specify the :uniq => true option to remove duplicates from the collection.

:validate

If you set the :validate option to false, then associated objects will not be validated whenever you save this object. By default, this is true: associated objects will be validated when this object is saved.

When are Objects Saved?

When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.

If any of these saves fails due to validation errors, then the assignment statement returns false and the assignment itself is cancelled.

If the parent object (the one declaring the has_and_belongs_to_many association) is unsaved (that is, new_record? returns true) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.

If you want to assign an object to a has_and_belongs_to_many association without saving the object, use the collection.build method.

Association Callbacks

Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a :before_save callback to cause something to happen just before an object is saved.

Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:

  • before_add
  • after_add
  • before_remove
  • after_remove

You define association callbacks by adding options to the association declaration. For example:

class Customer < ActiveRecord::Base
has_many :orders, :before_add => :check_credit_limit

def check_credit_limit(order) โ€ฆ end

end

Rails passes the object being added or removed to the callback.

You can stack callbacks on a single event by passing them as an array:

class Customer < ActiveRecord::Base
has_many :orders,
:before_add => [:check_credit_limit, :calculate_shipping_charges]

def check_credit_limit(order) โ€ฆ end def calculate_shipping_charges(order) โ€ฆ end

end

If a before_add callback throws an exception, the object does not get added to the collection. Similarly, if a before_remove callback throws an exception, the object does not get removed from the collection.

Association Extensions

Youโ€™re not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:

class Customer < ActiveRecord::Base
has_many :orders do
def find_by_order_prefix(order_number)
find_by_region_id(order_number[0..2])
end
end
end

If you have an extension that should be shared by many associations, you can use a named extension module. For example:

module FindRecentExtension
def find_recent
where(โ€œcreated_at > ?โ€, 5.days.ago)
end
end

class Customer < ActiveRecord::Base
has_many :orders, :extend => FindRecentExtension
end

class Supplier < ActiveRecord::Base
has_many :deliveries, :extend => FindRecentExtension
end

To include more than one extension module in a single association, specify an array of modules:

class Customer < ActiveRecord::Base
has_many :orders,
:extend => [FindRecentExtension, FindActiveExtension]
end

Extensions can refer to the internals of the association proxy using these three accessors:

  • proxy_owner returns the object that the association is a part of.
  • proxy_reflection returns the reflection object that describes the association.
  • proxy_target returns the associated object for belongs_to or has_one, or the collection of associated objects for has_many or has_and_belongs_to_many.

Changelog

  • April 7, 2010: Fixed document to validate XHTML 1.0 Strict. Jaime Iniesta
  • April 19, 2009: Added :touch option to belongs_to associations by Mike Gunderloy
  • February 1, 2009: Added :autosave option Mike Gunderloy
  • September 28, 2008: Corrected has_many :through diagram, added polymorphic diagram, some reorganization by Mike Gunderloy . First release version.
  • September 22, 2008: Added diagrams, misc. cleanup by Mike Gunderloy (not yet approved for publication)
  • September 14, 2008: initial version by Mike Gunderloy (not yet approved for publication)
Clone this wiki locally