我可以在has_many:through声明中使用扩展的活动记录关联吗?

时间:2012-12-05 20:11:11

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

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

示例:

我在我的图书馆模型中有这个:

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

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

1 个答案:

答案 0 :(得分:0)

看起来很像你想使用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 =&gt; true” - 你可能不得不说

where("meals.enabled=true")
与别名混淆的b / c。