-
Notifications
You must be signed in to change notification settings - Fork 3
Association basics.textile
๋ณธ ์๋ด๋ฌธ์๋ ์กํฐ๋ธ ๋ ์ฝ๋์ ์ฌ๋ฌ๊ฐ์ง ๊ด๊ณ(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 ๊ด๋ จ์ ๋ค๋ฅธ ๋ชจ๋ธ๊ณผ์ 1: 1 ์ฐ๊ด์ ์ ์ํ๋๋ฐ, ํ ๋ชจ๋ธ์ ์๊ฐ ๋ค๋ฅธ ๋ชจ๋ธ์ ์์ ์ํ๊ฒ ๋ฉ๋๋ค. ์๋ฅผ ๋ค์ด์, ๋น์ ์ ์์ฉ ํ๋ก๊ทธ๋จ์ด ์์ ์ค๋ช ํ ๊ณ ๊ฐ๊ณผ ์ฃผ๋ฌธ์ ํฌํจํ๋ค๊ณ ๊ฐ์ ํ๊ฒ ์ต๋๋ค. ์ด๋ ํ๋์ ์ฃผ๋ฌธ์ด ์ค์ง ํ๋์ ๊ณ ๊ฐ์๋ง ๊ด๋ จ๋์ด ์๋ค๋ฉด ๋น์ ์ ์ฃผ๋ฌธ ๋ชจ๋ธ์ ๋ค์๊ณผ ๊ฐ์ด ์ ์ธํ๊ฒ ๋ ๊ฒ์ ๋๋ค.
class Order < ActiveRecord::Base
belongs_to :customer
end
has_one ๊ด๋ จ ๋ํ ๋ค๋ฅธ ๋ชจ๋ธ๊ณผ์ 1:1 ๊ด๊ณ๋ฅผ ๊ท์ ํฉ๋๋ง ๋ค๋ฅธ ์๋ฏธ์ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ์ด๊ฒ ๋ฉ๋๋ค. ์ด ๊ด๊ณ๋ ํ๋์ ๋ชจ๋ธ์ ์ผ์๊ฐ ๋ค๋ฅธ ๋ชจ๋ธ์ ์ผ์๋ฅผ ์์ ํ๊ฑฐ๋ ํฌํจํ๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค. ์๋ฅผ ๋ค๋ฉด๋น์ ์ ์์ฉํ๋ก๊ทธ๋จ์์ ๊ตฌ๋งค๋ถ์์์ ์ฌ์ฉ๋๋ฉฐ ๋ฉํํ์ฌ๋ฅผ ๊ด๋ฆฐํ๋ค๊ณ ์นฉ์๋ค. ๊ฐ ๋ฉํํ์ฌ ๊ฐ๊ฐ ํ๋์ ๊ณ์ ์ ๊ฐ์ง๊ณ ์๋ค๋ฉด, ์ฐ๋ฆฌ๋ ์ด๋ฉํํ์ฌ๋ชจ๋ธ์ ๋ค์๊ณผ ๊ฐ์ด ์ ์ธํ ๊ฒ์ ๋๋ค.
class Supplier < ActiveRecord::Base
has_one :account
end
has_many ๋ค๋ฅธ ๋ชจ๋ธ๊ณผ 1:๋ค(ๅค:๋ง์) ๊ด๊ณ๋ฅผ ๋งํฉ๋๋ค. ์๋ง๋ ๋น์ ์ ์ด ๊ด๊ณ๊ฐ +belong_to+๊ด๊ณ์ ๋ฐ๋ ๊ด์ ์ด๋ผ๋ ๊ฒ์ ์๊ฒ ๋ ๊ฒ์ ๋๋ค. ์ด ๊ด๊ณ๋ ๋ค๋ฅผ ๋ชจ๋ธ์ ์๋ฅผ ํ๋๋ ๊ฐ์ง๊ณ ์์ง ์๊ฑฐ๋ ๋๋ ๋ณต์๊ฐ ๊ฐ์ง๊ณ ์์ ๋(์ฆ, 0๊ฐ์์ ์ฌ๋ฌ๊ฐ๋ฅผ ๊ฐ์ง๊ณ ์์ ๋) ์ ์ฌ์ฉํ๊ฒ ๋ฉ๋๋ค. ์๋ฅผ ๋ค๋ฉด, ๊ณ ๊ฐ๊ณผ ์ฃผ๋ฌธ์ ์ฒ๋ฆฌํ๋ ๋น์ ์ ์์ฉ ํ๋ก๊ทธ๋จ์์ ๊ณ ๊ฐ ๋ชจ๋ธ์ด ๋ค์๊ณผ ๊ฐ์ด ์ ์ธ๋ ์ ์๊ฒ ์ต๋๋ค.
class Customer < ActiveRecord::Base
has_many :orders
end
์ฃผ์: has_many B ๊ด๊ณ๋ฅผ ์ ์ธํ๋ ๊ฒฝ์ฐ์orders ์ ๊ฐ์ด B๊ฐ ๋ณต์ํ์ ์ด๋ฆ์ ๊ฐ๊ฒ๋๋ ๊ฒ์ ์ฃผ๋ชฉํด ์ฃผ์ธ์.
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
์ฐ๊ฒฐ๋ชจ๋ธ ์งํฉ์ 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 ๊ด๋ จ์ ๋ ๋ค๋ฅธ ๋ชจ๋ธ๊ณผ์ 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_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
๋ง์ฝ ๋น์ ์ด ๋ ๋ชจ๋ธ ์ฌ์ด์ 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
end
์ฃผ์: t.integer :supplier_id ์ ์ฌ์ฉ์ ์ธ๋ถ ์ด์ ์ ์ด๋ฆ์ ๋ช ํํ๊ฒ ํ๋ค. ํ์ฌ ๋ ์ผ์ฆ ๋ฒ์ ์์๋ ๋น์ ์+t.references :supplier+์ ์ฌ์ฉํ์ฌ ๊ตฌ์ฒด์ ์ธ ๊ตฌํ์ ์ถ์ํ ํ ์ ์๋ค.
๋ ์ผ์ฆ๋ ๋ชจ๋ธ๋ค๊ฐ์ ๋๊ฐ์ ๅค:ๅค ๊ด๊ณ๋ฅผ ์ ์ธํ๋ ๋ฐฉ๋ฒ์ ์ง์ํฉ๋๋ค. ๊ทธ์ค ๊ฐ๋จํ ๋ฐฉ๋ฒ์ 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๋ฅผ ์ฌ์ฉํ์ ์ผ ํฉ๋๋ค.
์ฝ๊ฐ์ ์ง์ผ๋ณดํ ๊ด๊ณ๋ก์จ, ํด๋ฆฌ๋ชจํฝ ๊ด๊ณ ๋ผ๋ ๊ฒ์ด ์์ต๋๋ค. ์ด ํด๋ฆฌ๋ชจํ ๊ด๊ณ๋ฅผ ์ด์ฉํ๋ฉด, ํ๋์ ๋ชจ๋ธ์ด ํ๋ ๋๋ ์ฌ๋ฌ ๋ชจ๋ธ์ ์ํ ์ ์์ต๋๋ค. ์๋ฅผ ๋ค๋ฉด, ์ฐ๋ฆฌ๊ฐ ์ฌ์ง(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
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
end
๋ฐ์ดํฐ ๋ชจ๋ธ์ ์ค๊ณํ ๋์ ๋น์ ์ ํ ๋ชจ๋ธ์ด ๊ทธ ๋ชจ๋ธ ์์ ๊ณผ ์ฐ๊ด์ด ์๋ ๊ฒฝ์ฐ๋ฅผ ์ข
์ข
๋ฐ๊ฒฌํ๊ฒ ๋ ๊ฒ์
๋๋ค. ์๋ฅผ ๋ค๋ฉด, ๋ชจ๋ ์ง์๋ค์ ํ๋์ ๋ฐ์ดํฐ ๋ฒ ์ด์ค ๋ชจ๋ธ๋ก ์ ์ฅํ๊ธธ ์ํ์ง๋ง, ์ง์๋ค ์ค ๊ด๋ฆฌ์(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? # ์ผ์ฌ๋ฅผ ๋ฌด์ํ๊ณ ๋ฐ์ดํฐ ๋ฒ ์ด์ค ์ฝ์
๊ด๊ณ๋ ๋๋จํ ์ ์ฉํฉ๋๋ค. ๊ทธ๋ ์ง๋ง ์ด๊ฒ์ด ๋ง์ ์ผ ์๋ ์์ต๋๋ค. ์ฐ๋ฆฌ์๊ฒ๋ ๊ด๊ณ์ ๋ฐ์ดํ ๋ฒ ์ด์ค ์คํค๋ง๊ฐ ๋ถํฉ ๋๋๋ก ๊ด๋ฆฌํ ์ฑ ์์ด ์์ต๋๋ค. ์ค์ฌ๋ก ์ด ๋ง์ ์ฐ๋ฆฌ๊ฐ ๋ง๋ค ๊ด๊ณ์ ์ข ๋ฅ์ ๋ฐ๋ผ์ ๋๊ฐ์ง ์๋ฏธ๋ฅผ ๊ฐ์ต๋๋ค. belongs_to ๊ด๊ณ๋ฅผ ์ฌ์ฉํ๋ค๋ฉด, ์ธ๋ ์ด์ ๋ฅผ ์์ฑํด์ผ ํ ๊ฒ์ด๊ณ , has_and_belongs_to_many ์ ๋ํด์๋ ์ฌ๋ฐ๋ฅธ ์ฐ๊ฒฐ ํ ์ด๋ธ์ ์์ฑํด์ผ ํฉ๋๋ค.
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
end
๋ง์ฝ ๋น์ ์ด ๋ชจ๋ธ์ ๋ง๋ ํ์ฐธ ํ์ ๊ด๊ณ๋ฅผ ์์ฑํ๋ค๋ฉด, ๋น์ ์ ํ์ํ ์ธ๋ ์ด์ ๋ฅผ ์ ๊ณตํ๊ณ ์ belongs_to ๋ง์ด๊ทธ๋ ์ด์ ์ ์์ฑํ๋ ๊ฒ์ ๊ธฐ์ตํด์ผ ํ๋ค.๋ง์ฝ ์ฐ๋ฆฌ๊ฐ+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
end
์ฐ๋ฆฌ๋+:id => false+ ๋ฅผ +create_table+๋ฅผ ์ธ์๋ก ๋๊ฒผ์ต๋๋ค. ๊ทธ ์ด์ ๋ ๊ทธ ํ ์ด๋ธ์ด ๋ชจ๋ธ์ ํํํ๊ณ ์์ง ์๊ธฐ ๋๋ฌธ์ด๋ฉฐ ์ ๋๋ก ์๋ํ๊ธฐ ์ํด์ ๊ด๊ณ๋ ๊ทธ๋ฌํ ์ธ์๊ฐ ํ์ํฉ๋๋ค. ๋ง์ฝ ๋น์ ์ด+has_and_belongs_to_many+๊ด๊ณ๋ฅผ ์ฌ์ฉํ ๋์ ๊นจ์ง ๋ชจ๋ธ ์์ด๋๋ ์์ด๋ ์ถฉ๋ ์์ธ์ฒ๋ฆฌ์ ๊ฐ์ ์ด์ํ ์ํ๊ฒฐ๊ณผ๋ฅผ ๋ฐ๊ฒฌํ๋ค๋ฉด, ์๋ง๋ ์ด์ ๊ฐ์ด ์ธ์๋ฅผ ๋๊ธฐ์ง ์์๊ธฐ ๋๋ฌธ์ผ ์ ์์ต๋๋ค.
๊ธฐ๋ณธ์ผ๋ก ๊ด๊ณ๋ ํ ๋ชจ๋ธ์ ๋ฒ์๋ด์์ ๊ฐ์ฒด์ ์๋ค์ ์ฐพ์ต๋๋ค. ์ด๊ฒ์ ์ฐ๋ฆฌ๊ฐ ํ์ฑ ๋ ์ฝ๋ ๋ชจ๋ธ์ ์ ์ธํ ๋์ ์ค์ํ ์ ์์ต๋๋ค. ๋ค์ ์๋ฅผ ๋ณด์์ฃ .
module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end
end
์ด ์์ ์ฝ๋๋ ๋ฌธ์ ์์ด ์๋ ํ ๊ฒ์
๋๋ค. ์๋ํ๋ฉด+Supplier+ ์ Account ๊ฐ์ฒด๊ฐ ๋์ผํ ๋ฒ์, ์ฆ, ๋ชจ๋๋ด์์ ์ ์๊ฐ ๋๊ธฐ ๋๋ฌธ์
๋๋ค. ๋ฐ๋๋ก, ๋ค์์ ์์์๋ Supplier ์ Account ์ ๋๋ก ์๋ํ์ง ์์ํ
๋ฐ ๊ทธ ์ด์ ๋ ์ด๋ค์ด ๋ค๋ฅธ ๋ฒ์์์ ์ ์๋๊ธฐ ๋๋ฌธ์ด์ฃ .
module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account
end
end
end
๋ค๋ฅธ ์ด๋ฆ๊ณต๊ฐ(namespace)์ ์ ์๋ ๋ชจ๋ธ๋ค ์ฌ์ด๋ฅผ ๊ด๊ณ ๋งบ๊ณ ์ ํ ๊ฒฝ์ฐ, ์ฐ๋ฆฌ๋ ์์ ํ ๊ฐ์ฒด ๋ช ์ ๊ด๊ณ์ ์์ ๋ช ์ํด์ผ ๋ฉ๋๋ค. ๋ค์์ ๋ณด์์ฃ .
module MyApplication
module Business
class Supplier < ActiveRecord::Base
has_one :account,
:class_name => โMyApplication::Billing::Accountโ
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 ๊ด๊ณ๋ ๋ค๋ฅธ ๋ชจ๋ธ๊ณผ์ 1:1 ๊ด๊ณ๋ฅผ ์์ฑํ๋ค. ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฉ์ด๋ก๋ ์ด ๊ด๊ณ๊ฐ์ฒด๊ฐ ์ธ๋ ์ด์ ๋ฅผ ๊ฐ๊ฒ๋๋ค๊ณ ๋งํฉ๋๋ค. ๋ง์ฝ ๊ด๋ จ๋ ๋ค๋ฅธ ๊ฐ์ฒด๊ฐ ์ธ๋ ์ด์ ๋ฅผ ๊ฐ์ง๊ฒ ๋๋ค๋ฉด, ์ฐ๋ฆฌ๋+has_one+ ๊ด๊ณ๋ฅผ ๋์ ์ฌ์ฉํด์ผ ํฉ๋๋ค.
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
@customer = @order.customer
๋ง์ฝ ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ก๋ถํฐ ๊ด๋ จ๊ฐ์ฒด์ ๋ฒ์จ ์ฝ์๋ค๋ฉด ์ด ๊ฒ์ ์์์ ์ฅ์(์ผ์ฌ)์ ๊ฒ์ด ๋ฐํ๋ ๊ฒ์ ๋๋ค. ์บ์ฌ์ ๊ฒ์ ์ฌ์ฉํ๋ ์ด ๋ฐฉ๋ฒ์ ๋ฌด์ํ๊ณ ๋ฐ์ดํฐ ๋ฒ ์ด์ค์ ๊ฒ์ ์ฝ๊ธฐ๋ฅผ ์ํ๋ค๋ฉด, force_reload ์ ํด๋นํ๋ ์ธ์๊ฐ์ true ๋ก ๋๊ธฐ์ ์ผ ํฉ๋๋ค.
association= ๋ฉ์๋๋ ๊ด๋ จ๋ ๊ฐ์ฒด๋ฅผ ์ค์ ํ ๊ฒ์ ๋๋ค. ๋ด๋ถ์ ์ผ๋ก ์ด๊ฒ์ ๊ด๋ จ ๊ฐ์ฒด์ (๋ฐ์ดํฐ ๋ฒ ์ด์ค์) ์ฃผ ์ด์ ๊ฐ์ ๊บผ๋ด์ (๋ฐ์ดํฐ๋ฒ ์ด์ค์) ์ธ๋ถ ์ด์ ๋ก ๋ณต์ฌํ๋ ๊ฒ๊ณผ ๊ฐ์ต๋๋ค.@order.customer = @customer
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โ)
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โ)
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
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.
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
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
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.
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.
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.
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.
Passing true to the :polymorphic option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
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.
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
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.
To know whether thereโs and associated object just check association.nil?:
if @order.customer.nil?
@msg = โNo customer found for this orderโ
end
Assigning an object to a belongs_to association does not automatically save the object. It does not save the associated object either.
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.
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.
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.
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
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โ)
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โ)
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
Setting the :as option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.
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.
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
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
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.
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.
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
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.
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.
If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.
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.
The :source option specifies the source association name for a has_one :through association.
The :source_type option specifies the source association type for a has_one :through association that proceeds through a polymorphic association.
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.
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.
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 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.
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.
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 = {})
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
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
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.
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
The collection_singular_ids method returns an array of the ids of the objects in the collection.
@order_ids = @customer.order_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.
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.
The collection.empty? method returns true if the collection does not contain any associated objects.
<% if @customer.orders.empty? >
No Orders Found
< end %>
The collection.size method returns the number of objects in the collection.
@order_count = @customer.orders.size
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.
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
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?.
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โ)
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โ)
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
Setting the :as option indicates that this is a polymorphic association, as discussed earlier in this guide.
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.
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
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.
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.
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.
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
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.
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.
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
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
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
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.
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
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.
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
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.
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.
The :source_type option specifies the source association type for a has_many :through association that proceeds through a polymorphic association.
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.
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.
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 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.
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.
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 = {})
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.
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
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.
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)
The collection= method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
The collection_singular_ids method returns an array of the ids of the objects in the collection.
@assembly_ids = @part.assembly_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.
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.
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 %>
The collection.size method returns the number of objects in the collection.
@assembly_count = @part.assemblies.size
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.
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)
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?.
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โ})
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โ})
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
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
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.
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
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โ.
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.
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.
The :extend option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.
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.
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
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
You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.
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.
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.
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
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.
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
If you set the :readonly option to true, then the associated objects will be read-only when retrieved via the association.
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.
Specify the :uniq => true option to remove duplicates from the collection.
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 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.
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
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]
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.
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.
- 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)