在Rails belongs_to关联中inverse_of做了什么?

时间:2016-05-08 08:54:15

标签: ruby-on-rails ruby-on-rails-4

首先,我知道inverse_of在has_many关联中是如何工作的。

# relationship without inverse_of
user has_many :orders

# this will generate two database queries
user.orders.first.user
Order Load (0.1ms)  SELECT  `orders`.* FROM `orders` WHERE `orders`.`user_id` = 2  ORDER BY `orders`.`id` ASC LIMIT 1
User Load (0.1ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1

这里,user和user.order.first.user是两个不同的对象。

并使用inverse_of

# relationship with inverse_of
user has_many :orders, inverse_of: :user

# this will generate just one database query
user.orders.first.user
Order Load (0.1ms)  SELECT  `orders`.* FROM `orders` WHERE `orders`.`user_id` = 2  ORDER BY `orders`.`id` ASC LIMIT 1

现在,user和user.order.first.user是同一个对象。

但是,这个belongs_to关联中有什么inverse_of呢?

# relationship with inverse_of in belongs_to association
order belongs_to :user, inverse_of: :orders

order.user.orders
# will generate two database queries
User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
Order Load (0.1ms)  SELECT `orders`.* FROM `orders` WHERE `orders`.`user_id` = 2

如果我在此关系中使用inverse_of或不使用inverse_of,则没有区别。那么,也许我以错误的方式使用它?在belongs_to关联中,inverse_of的重点是什么?

1 个答案:

答案 0 :(得分:0)