Squeel and rails… dynamic where clause

前端 未结 2 1325
眼角桃花
眼角桃花 2021-01-20 12:51

Using Squeel, in a rails app, I have a hash of conditions:

{\'trans\' => \'manual\'}

which i eventually plan on moving into an array...

2条回答
  •  心在旅途
    2021-01-20 13:26

    I don't know if this helps, but I did it this way using this helper method:

      def query_for_matches(key, value)
        stub = Squeel::Nodes::Stub.new(key)
        Squeel::Nodes::Predicate.new(stub, :matches, "%#{value}%")
      end
    

    You have a hash of parameters from a request of something:

      dynamic_params = {'username' => 'some_name', 'email' => 'email@example.com'}
    

    Then I use this with a chain of where's in a loop:

      query = SomeModel #could be User, etc
      dynamic_params.each_pair {|key,value| query = query.where(query_for_matches(key, value)) }
    

    You can then pass query to your view or whatever. I've only been on rails for a couple of weeks so I'm not sure if this is a best practice but it works.

提交回复
热议问题