Rails has_one : 通过关联 [英] Rails has_one :through association
问题描述
Rails 有一个 has_one :through
关联,它帮助通过第二个模型与第三个模型建立一对一的关联.除了建立快捷方式关联之外,它的真正用途是什么,否则会多走一步.
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.
以 Rails 指南为例:
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
否则将达到:
supplier.account.history
如果只是为了更简单的访问,那么从技术上讲,可能存在一对一的关联,将模型与通过 n-1 个模型的某个第 n 个模型连接起来,以便于访问.除了快捷方式之外,我还缺少其他什么吗?
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 sound 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 the entire account history of this supplier", so it makes sense for me to be able to access account history from supplier directly.
效率,这对我来说是我使用 :through
的主要原因,仅仅是因为这会发出一个 join 语句而不是调用供应商,然后帐户,然后是 account_history.注意到数据库调用的次数了吗?
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?
使用
:through
,1 次调用获取供应商,1 次调用获取account_history(rails 自动使用:join
通过帐户检索)
using
:through
, 1 call to get the supplier, 1 call to get account_history (rails automatically uses:join
to retrieve through account)
使用正常关联,1次调用获取供应商,1次调用获取帐户,1次调用获取account_history
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屋!