Squeel and rails… dynamic where clause

前端 未结 2 1324
眼角桃花
眼角桃花 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:35

    You need to programmatically build the Squeel query. For example:

    def self.with_conditions(conditions)
      conditions.map do |col, str|
        Squeel::Nodes::Predicate.new(Squeel::Nodes::Stub.new(col), :matches, str) # (email.matches "user@example.com")
      end.inject do |t, expr|
        t & expr # joins each expression from the .map above with & - to be converted to AND in the sql
      end.tap do |block|
        return where{(block)} # pass the constructed expression to Squeel
      end
    end
    

    On my User::User model I can run

    User::User.with_conditions({email: "user@example.com", first_name: "Deefour"}).to_sql
    

    and I will get

    SELECT "user_users".* FROM "user_users"  WHERE (("user_users"."email" LIKE 'user@example.com' AND "user_users"."first_name" LIKE 'Deefour'))
    

提交回复
热议问题