Rails的HAS_ONE:通过协会 [英] Rails has_one :through association
问题描述
Rails有一个 HAS_ONE:通过帮助通过第二个模型会设置了第三个模型一比一的关联
关联。什么是真正的使用,除了做一个快捷方式的关联,否则将是一个额外一步之遥。
以从Rails的指南这个例子:
类供应商< ActiveRecord的::基地
HAS_ONE:帐户
HAS_ONE:account_history,:通过=> :帐户
结束类账户< ActiveRecord的::基地
belongs_to的:供应商
HAS_ONE:account_history
结束类AccountHistory< ActiveRecord的::基地
belongs_to的:帐户
结束
可能会允许我们做一些事情,如:
supplier.account_history
,否则达到为:
supplier.account.history
如果它只是更简单的访问,然后在技术上有可能是一个一对一的关联,与一些第n模式经历N-1模型更轻松地访问连接的模型。还有什么吧,我除了快捷失踪?
-
逻辑后,确定它可能听起来这有点弱,但它是合乎逻辑地说,我有谁与我的帐户供应商,我希望看到所有的该供应商的帐户历史记录,因此它是有道理的,我能够从供应商访问的帐户历史记录直
-
效率,这对我来说是最主要的原因我会用:通过,仅仅是因为这发出连接语句,而不是调用的供应商,然后帐户,然后account_history。注意到数据库调用的次数?
-
使用:通过,1调用来获取供应商,1呼吁得到account_history(导轨自动使用:通过加入帐户检索)
- 使用正常的关联
1个call得到供应商,1调用来获取账户,1个呼叫得到account_history
-
这就是我认为=)希望它能帮助!
Rails has a has_one :through
association that helps set up a one-to-one association with a third model by going through a second model. What is the real use of that besides making a shortcut association, that would otherwise be an extra step away.
Taking this example from the Rails guide:
class Supplier < ActiveRecord::Base
has_one :account
has_one :account_history, :through => :account
end
class Account < ActiveRecord::Base
belongs_to :supplier
has_one :account_history
end
class AccountHistory < ActiveRecord::Base
belongs_to :account
end
might allow us to do something like:
supplier.account_history
which would otherwise be reached as:
supplier.account.history
If it's only for simpler access then technically there could be a one-to-one association that connects a model with some nth model going through n-1 models for easier access. Is there anything else to it that I am missing besides the shortcut?
Logic, ok it might sounds a bit weak for this but it would be logical to say that "i have a supplier who has an account with me, i want to see all the account history of this supplier", so it makes sense for me to be able to access account history from supplier straight
Efficiency, this for me is the main reason i would use :through, simply because this issues a join statement rather than calling supplier, and then account, and then account_history. noticed the number of database calls?
using :through, 1 call to get the supplier, 1 call to get account_history (rails automatically used :join to retrieve through account)
using normal association, 1 call to get supplier, 1 call to get account, and 1 call to get account_history
that's what i think =) hope it helps!
这篇关于Rails的HAS_ONE:通过协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!