有没有办法使用命名范围过滤连接关联?

时间:2009-07-27 09:16:33

标签: ruby-on-rails named-scope

我有以下相关模型

class Enrollment < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :address_type
end

目前,我正在使用以下内容(我认为很难看)来过滤掉某种地址类型的注册地址。

class Enrollment < ActiveRecord::Base
  def local_address
    adds = []
    addresses.each do |add| 
      adds << add if add.address_type.name == 'Local'
    end
    adds.last
  end
end

有没有办法使用命名范围做同样的事情?

2 个答案:

答案 0 :(得分:0)

通用解决方案:

class Address < ActiveRecord::Base
  belongs_to :address_type
  named_scope :local, { :conditions => { :address_type => { :name => "Local" }}}
end

这允许您执行以下操作:

Enrollment.find(12).addresses.local  # Association extended with .local method
Address.local.all                    # Class methods extended with .local method

在您使用“本地”地址的所有情况下,命名范围可能会有所帮助。

答案 1 :(得分:0)

参考下面的stackoverflow帖子,我设法解决了我的命名范围查询

Rails named_scopes with joins

基本上我需要在查询中进行连接

class Address < ActiveRecord::Base
  belongs_to :address_type
  named_scope :local, { 
    :joins => "INNER JOIN address_types ON address_types.id = addresses.address_type_id",
    :conditions => "address_types.name = 'Local'"
  }
end

所以我可以有效地将我的Enrollment的“local_address”方法重写为

clss Enrollment < ActiveRecord::Base
    def local_address
      addresses.local.last
    end
end