如何使用Squeel进行内置查询?

时间:2015-01-16 09:24:34

标签: ruby-on-rails activerecord squeel

我想使用squeel构建一个查询构建器,以下是我的工作方式:

家长班:

module ModelFilters
  class Base
    def initialize(user)
      @user = user
    end

    def build(method_name)
      head.where { my { send(method_name) } }
    end

    protected

    def head
    end
  end
end

儿童班:

module ModelFilters
  class Collection < Base
    def __showable__
      not_private | author
    end

    protected

    def head
      ::Collection.joins(:collaborators)
    end

    private

    def not_private
      is_private == false
    end

    def author
      user_id == @user.id
    end
  end
end

最后我的电话:

a = ModelFilters::Collection.new(user)
a.build(:__showable__)

其实我的问题是我不知道Squeel如何为innested查询工作,我的实际错误是undefined local variable or method 'is_private'(显然)。

有没有办法使用Squeel(或其他ActiveRecord查询构建器)构建这样的东西?

谢谢大家!

1 个答案:

答案 0 :(得分:2)

如果你这样做:

module ModelFilters
  class Base
    def initialize(user)
      @user = user
    end

    def build(method_name)
      head.where { |q| send(method_name, q) }
    end

    protected

    def head
    end
  end
end

module ModelFilters
  class Collection < Base
    def __showable__(q)
      not_private(q) | author(q)
    end

    protected

    def head
      ::Collection.joins(:collaborators)
    end

    private

    def not_private(q)
      q.is_private == false
    end

    def author(q)
      q.user_id == @user.id
    end
  end
end