ruby-on-rails – Rails 3将范围与连接合并

建立

对于这个问题,我将使用以下三个类:

class Solarsystem < ActiveRecord::Base
  has_many :planets

  scope :has_earthlike_planet,joins(:planets).merge(Planet.like_earth)
end

class Planet < ActiveRecord::Base
  belongs_to :solar_system
  belongs_to :planet_type

  scope :like_earth,joins(:planet_type).where(:planet_types => {:life => true,:gravity => 9.8})
end

class PlanetType < ActiveRecord::Base
  has_many :planets

  attr_accessible :gravity,:life
end

问题

范围has_earthlike_planet不起作用.它给了我以下错误

ActiveRecord::ConfigurationError: Association named ‘planet_type’ was
not found; perhaps you misspelled it?

我发现这是因为它等同于以下内容

joins(:planets,:planet_type)...

和Solarsystem没有planet_type关联.我想在Planet上使用like_earth范围,在Solarsystem上使用has_earthlike_planet,并且希望避免重复代码和条件.有没有办法合并这些范围,就像我试图做但却缺少一块?如果没有,我可以用什么其他技术来实现这些目标?

解决方法

显然,此时您只能合并不涉及连接的简单构造.如果您将模型修改为如下所示,这是一种可能的解决方法
class Solarsystem < ActiveRecord::Base
  has_many :planets
  has_many :planet_types,:through => :planets

  scope :has_earthlike_planet,joins(:planet_types).merge(PlanetType.like_earth)
end

class Planet < ActiveRecord::Base
  belongs_to :solar_system
  belongs_to :planet_type

  scope :like_earth,joins(:planet_type).merge(PlanetType.like_earth)
end

class PlanetType < ActiveRecord::Base
   has_many :planets

   attr_accessible :gravity,:life

   scope :like_earth,where(:life => true,:gravity => 9.8)
end

**更新**

为了记录,关于这种行为的bug was filed – 希望很快就会修复……

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...