【问题标题】:Can I use an extended active record association in a has_many :through declaration?我可以在 has_many :through 声明中使用扩展的活动记录关联吗?
【发布时间】:2012-12-05 20:11:11
【问题描述】:

我已经扩展了我的许多 has_many 声明来过滤/加入/预加载关联。当我声明 has_many :through 关系时,我想重新使用其中的一些扩展。这可能吗?我应该采取不同的方法吗?

例子:

我的库模型中有这个:

class Library < ActiveRecord::Base
  has_many :meals, :dependent => :destroy do
    def enabled
      where(:enabled => true)
    end
  end
end

我的膳食模型有这个:

class Meal < ActiveRecord::Base
  has_many :servings, :inverse_of => :meal, :dependent => :destroy
end

我希望我的图书馆有很多份,但仅限于启用的膳食。有几种方法可以做到这一点:

# repeat the condition in the has_many :servings declaration
class Library < ActiveRecord::Base
  has_many :servings, :through => :meals, :conditions => ["meals.enabled = ?", true]
end

# declare a different meals association for only the enabled meals
class Library < ActiveRecord::Base
  has_many :enabled_meals, :class_name => "Meals", :conditions => [:enabled => true]
  has_many :servings, :through => :enabled_meals
end

有没有办法重新使用我现有的 :meals 声明的扩展?(在第一个代码块中启用了 def)

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3.2


    【解决方案1】:

    看起来很像您想使用 activerecord-association-extensions,如此处所述http://blog.zerosum.org/2007/2/8/activerecord-association-extensions.html

    我没试过,但我认为你可以这样做:

      module LibraryMealExtensions
      def enabled?
        where(:enabled=>true)
      end
    
      def standard_includes
        includes(:servings)
      end
    end
    
    class Library < ActiveRecord::Base
      has_many :meals, :dependent => :destroy, :extend=>LibraryMealExtensions
      has_many :servings, :through => :meals, :extend=>LibraryMealExtensions
    end
    

    不确定那里的“enabled=>true” - 你可能不得不说

    where("meals.enabled=true")
    

    b/c 混淆别名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2011-02-17
      • 2013-05-30
      相关资源
      最近更新 更多