微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/264720.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐