加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:22:55 所属栏目:百科 来源:网络整理
导读:建立 对于这个问题,我将使用以下三个类: class SolarSystem ActiveRecord::Base has_many :planets scope :has_earthlike_planet,joins(:planets).merge(Planet.like_earth)endclass Planet ActiveRecord::Base belongs_to :solar_system belongs_to :plane
建立

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

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 – 希望很快就会修复……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读