首页 > 代码库 > rails 中model之间的 association (:inverse_of)

rails 中model之间的 association (:inverse_of)

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 关联不会自动逆转!