0

假设我有两个模型

class Client < ActiveRecord::Base
  has_many :accounts
end

class Account < ActiveRecord::Base
  belongs_to :client
end

现在,我想要一种方便的方法来访问已批准的帐户(:approved => true)。什么更好用,为什么?

  1. has_many: approved_accounts, -> { where :approved => true }对于Client模型

  2. scope: approved, -> { where :approved => true }用于Account模型
4

2 回答 2

1

据我说,scope解决方案似乎更好:

您可能知道,要获得客户的批准帐户,您可以执行approved_accounts = client.accounts.approved以下操作:approved_accounts = client.approved_accounts

所以这里没有太大区别。但是,如果将来您想要所有已批准帐户的列表(用于统计或其他),使用范围解决方案,一个approved_accounts = Account.approved就足够了。但是如果你选择客户端,获取起来会比较棘手(理解:你将不得不使用客户端模型)。

只需考虑比被批准更多的是账户的财产而不是客户的财产,并且应该更清楚的是范围是最佳解决方案。

希望这可以澄清事情。

于 2013-08-04T16:12:43.183 回答
1

简短的回答,这取决于。对于长答案,请继续阅读...

  • 条件关联允许我们自定义ActiveRecord用于获取关联的查询。当您确定此条件是永久性的并且您永远不需要访问不符合条件的数据(至少不在此模型中)时使用,因为条件关联适用于每个查询以ActiveRecord执行来自该特定的关联模型。

  • Scope It is basically, a class method for retrieving and querying objects. so what you are actually doing is defining the following method in your model.

    class Client < ActiveRecord::Base self.approved where(:approved => true) end end

so scope is generally use to define short names for one or more regularly used query customization. But important difference is that scope is not auto-applied unless you use default_scope but conditional associations are auto-applied.

In your case, you want to show unapproved accounts in this model? If not, then use conditional association. Else use scope

于 2013-08-04T16:35:12.073 回答