rails dynamic where sql query

后端 未结 1 1363
名媛妹妹
名媛妹妹 2021-01-23 20:30

I have an object with a bunch of attributes that represent searchable model attributes, and I would like to dynamically create an sql query using only the attributes that are se

1条回答
  •  醉梦人生
    2021-01-23 20:57

    Your approach is a little off as you're trying to solve the wrong problem. You're trying to build a string to hand to ActiveRecord so that it can build a query when you should simply be trying to build a query.

    When you say something like:

    Model.where('a and b')
    

    that's the same as saying:

    Model.where('a').where('b')
    

    and you can say:

    Model.where('c like ?', pattern)
    

    instead of:

    Model.where("c like '#{pattern}'")
    

    Combining those two ideas with your self.instance_values you could get something like:

    def query
      self.instance_values.select { |_, v| v.present? }.inject(YourModel) do |q, (name, value)|
        q.where("#{name} like ?", "%#{value}%")
      end
    end
    

    or even:

    def query
      empties      = ->(_, v) { v.blank? }
      add_to_query = ->(q, (n, v)) { q.where("#{n} like ?", "%#{v}%") }
      instance_values.reject(&empties)
                     .inject(YourModel, &add_to_query)
    end
    

    Those assume that you've properly whitelisted all your instance variables. If you haven't then you should.

    0 讨论(0)
提交回复
热议问题