How to specify multiple values in where with AR query interface in rails3

前端 未结 7 1056
时光说笑
时光说笑 2020-12-28 13:31

Per section 2.2 of rails guide on Active Record query interface here:

which seems to indicate that I can pass a string specifying the condition(s), then an array of

7条回答
  •  既然无缘
    2020-12-28 14:00

    WRONG This is what I used to do for some reason.

    keys = params[:search].split(',').map!(&:downcase)
    # keys are now ['brooklyn', 'queens']
    
    query = 'lower(city) LIKE ?'
    
    if keys.size > 1
      # I need something like this depending on number of keys 
      # 'lower(city) LIKE ? OR lower(city) LIKE ? OR lower(city) LIKE ?'
     query_array = []
     keys.size.times { query_array << query }
     #['lower(city) LIKE ?','lower(city) LIKE ?']
     query = query_array.join(' OR ')
     # which gives me 'lower(city) LIKE ? OR lower(city) LIKE ?'
    end
    # now I can query my model
    # if keys size is one then keys are just 'brooklyn', 
    # in this case it is  'brooklyn', 'queens'
    # @posts = Post.where('lower(city) LIKE ? OR lower(city) LIKE ?','brooklyn', 'queens' )
    @posts = Post.where(query, *keys )
    

    now however - yes - it's very simple. as nfriend21 mentioned

    Model.where(attribute: [value1,value2])

    does the same thing

提交回复
热议问题