Sambhav Sharma
Sambhav Sharma

Reputation: 5860

Rails dynamic attribute in where LIKE clause

I have a search method, which takes in a key value pair in argument and searches on an active record model via a LIKE query. But I am unable to get it to work. It doesn't take the key argument properly.

This is what my method looks like:

def search(key,value)
  where('? LIKE ?',key,"%#{value}%")
end

The query it fires is ('name' LIKE '%air%') whereas it should fire (name LIKE '%air%')

Is there a way I could get this to work?

Upvotes: 2

Views: 1381

Answers (2)

Ven
Ven

Reputation: 19039

Warning: The solution proposed by @MKumar is very dangerous. If key is user-input, you just allowed SQL injection.

def search(key, value)
  where("#{key} LIKE ?", "%#{value}%")
end
search("IS_ADMIN == 1 --", "")

Whoops!

The better way to do this would be to use Arel tables.

def search(key, value)
  column = Model.arel_table[key.to_sym] # index into the columns, via a symbol
  where(column.matches("%#{value}%"))
end

This cannot produce a SQL injection.

Upvotes: 6

Sachin R
Sachin R

Reputation: 11876

Try like this

def search(key,value)
  where("#{key} LIKE ?","%#{value}%")
end

Upvotes: 0

Related Questions