首页 > 其他 > 详细

rails 中model之间的 association (:inverse_of)

时间:2014-07-10 10:02:14      阅读:663      评论:0      收藏:0      [点我收藏+]

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

rails 中model之间的 association (:inverse_of),布布扣,bubuko.com

rails 中model之间的 association (:inverse_of)

原文:http://www.cnblogs.com/perish/p/3812301.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!