gpt4 book ai didi

ruby-on-rails - Rails 3 合并作用域与连接

转载 作者:行者123 更新时间:2023-12-04 14:03:16 25 4
gpt4 key购买 nike

设置

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

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协会。我想使用 like_earth范围在 Planet , has_earthlike_planetSolarSystem ,并希望避免重复代码和条件。有没有办法像我试图做的那样合并这些范围,但我错过了一部分?如果没有,我可以使用哪些其他技术来实现这些目标?

最佳答案

显然,此时您只能合并不涉及连接的简单构造。如果您将模型修改为如下所示,这是一种可能的解决方法:

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关于这种行为 - 希望很快就会得到修复......

关于ruby-on-rails - Rails 3 合并作用域与连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13036604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com