gpt4 book ai didi

ruby-on-rails - 使用 ActiveRecord 在 rails 3 中 inverse_of 的限制是什么

转载 作者:行者123 更新时间:2023-12-04 12:55:02 25 4
gpt4 key购买 nike

我一直在阅读有关 inverse_of 的文章,而我在网上看到的所有内容似乎都不一致并使我感到困惑。如果你看 here ,你可以看到

There are a few limitations to inverse_of support:

  • They do not work with :through associations.
  • They do not work with :polymorphic associations.
  • They do not work with :as associations.
  • For belongs_to associations, has_many inverse associations are ignored.


然而就在这之上,他们给出了这个例子
class Customer < ActiveRecord::Base
has_many :orders, :inverse_of => :customer
end

class Order < ActiveRecord::Base
belongs_to :customer, :inverse_of => :orders
end

我认为他们是说第一个 inverse_of 什么都不做,但如果是这样,他们为什么要这样做?

此外,即使上面说的 inverse_of 不适用于通过关联, this page

If you are using a belongs_to on the join model, it is a good idea to set the :inverse_of >option on the belongs_to, which will mean that the following example works correctly where >tags is a has_many :through association):



并给出这个例子
@post = Post.first
@tag = @post.tags.build :name => "ruby"
@tag.save

The last line ought to save the through record (a Taggable). This will only work if the >:inverse_of is set:


class Taggable < ActiveRecord::Base
belongs_to :post
belongs_to :tag, :inverse_of => :taggings
end

对我来说,所有这些似乎不一致且非常困惑。但总的来说,我认为对每个关系都说 inverse_of 没有什么坏处。那是问题吗?我看到很多人在 SO 上问过这个问题,但没有看到任何人给出肯定的"is"或“否”。

最佳答案

总是指定它没有什么坏处,它将允许 rails 优化对象的加载,这样您就可以在两个方向上上下事件记录模型关系链,而不会出现奇怪的错误,即更改一个对象上的值不会改变它的引用.

将它设置为不起作用的唯一问题是您之前所说的某些类型,如果它们无声地失败,如果您在更改某些内容后在方法链中走错了路,您将获得上述错误

这是来自 rails API

d = Dungeon.first
t = d.traps.first
d.level == t.dungeon.level # => true
d.level = 10
d.level == t.dungeon.level # => false

上例中的 Dungeon 实例 d 和 t.dungeon 引用了来自数据库的相同对象数据,但实际上是该数据的不同内存副本。在关联上指定 :inverse_of 选项可以让你告诉 Active Record 关于反向关系,它会优化对象加载。

关于ruby-on-rails - 使用 ActiveRecord 在 rails 3 中 inverse_of 的限制是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16076823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com