在PORO中链接ActiveRecord_Relation

时间:2018-11-09 04:31:24

标签: ruby-on-rails arel

在Rails 5.1应用程序中,我有一个名为CoolProducts的查询对象(PO​​RO)。

class CoolProducts
  def self.call(relation = Product.all)
  ...
  # return an instance of Product::ActiveRecord_Relation
  end
end

现在我需要基于Productname匹配的事实来限制找到的string

以下作品

CoolProducts.call.where("name ILIKE ?", "%#{string}%")

但是,我想将匹配的登录名封装在CoolProducts类中,以允许执行类似的操作

CoolProducts.call.including_in_name(string)

但是我不确定从哪里开始。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果要使任何方法可链接或返回ActiveRecord :: Relation,将很困难。

如果您考虑在完成链接后可以显式获取记录,则应该可以:

class CoolProducts
  def initialize(relation)
    @relation = relation
  end

  def self.call(relation = Product.all)
    new(relation).apply_scopes
  end

  attr_reader :relation
  alias_method :fetch, :relation

  def including_in_name(string)
    tap { @relation = relation.where("name ILIKE ?", string) }
  end

  def apply_scopes
    tap { @relation = relation.where(price: 123) }
  end
end

用法:

CoolProducts.call.including_in_name(string).fetch
相关问题