標籤:資料 cti for io 代碼 re
class Customer < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :customer
end
如上代碼兩個model在做如下查詢的時候:
c = Customer.first
o = c.orders.first
c.first_name == o.customer.first_name # true
c.first_name = "other name"
c.first_name == o.customer.first_name # false
這是因為c 和 o.customer 在記憶體中兩個對象對應的同一個資料
當在model中添加 :inverse_of 的時候就會出現這種情況:
class Customer < ActiveRecord::Base
has_many :orders, inverse_of: :customer
end
class Order < ActiveRecord::Base
belongs_to :customer, inverse_of: :orders
end
####
o = c.orders.first
c.first_name == o.customer.first_name # true
c.first_name = "other name"
c.first_name == o.customer.first_name # true
當添加了inverse_of ,只會載入一個customer對象
在用inverse_of的時候是有限制的:
有這些條件:through :polymorphic :as 的時候,因為有belongs_to和has_many, inverse_of 這個會被忽略!
當有這些條件的時候
:conditions
:through
:polymorphic
:foreign_key 關聯不會自動逆轉!