Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 有没有一种方法可以使用命名作用域过滤加入的关联?_Ruby On Rails_Named Scope - Fatal编程技术网

Ruby on rails 有没有一种方法可以使用命名作用域过滤加入的关联?

Ruby on rails 有没有一种方法可以使用命名作用域过滤加入的关联?,ruby-on-rails,named-scope,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
  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
班级注册
class Address < ActiveRecord::Base
  belongs_to :address_type
  named_scope :local, { :conditions => { :address_type => { :name => "Local" }}}
end

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

参考下面的stackoverflow帖子,我成功地解决了命名范围查询

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

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
类地址“地址类型上的内部连接地址类型。id=地址。地址类型\U id”,
:conditions=>“address_types.name='Local'”
}
终止
因此,我可以有效地将注册的“本地地址”方法重写为

clss Enrollment < ActiveRecord::Base
    def local_address
      addresses.local.last
    end
end
clss注册
您的解决方案出现以下错误。Mysql::错误:“where子句”中的未知列“address\u type.name”:从
addresses
where(
addresses
.incrolment\u id=8)和(
address\u type
name
='Local')以及(
addresses
.incrolment\u id=8))按地址排序。id DESC LIMIT 1似乎我们必须使用join语句。
clss Enrollment < ActiveRecord::Base
    def local_address
      addresses.local.last
    end
end