Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable in ActiveRecord where condition

I have a condition to filter/search the title and user of the post based on the some search keywords.

As you can see the values can be used in where conditions as below two types:

Post.where('title ILIKE :keyword or user_name ILIKE :keyword', keyword: "%#{params[:search_keyword]}%")

Post.where('title ILIKE ? or user_name ILIKE ?', "%#{params[:search_keyword]}%", "#{%params[:search_keyword]}%")

First one is by using variable directly inside conditions and second one is using the ? symbol. And first one is easy for me if, there are many variables to compare as I can declare a variable once and use it many times.

Can anyone tell me is there is any disadvantage or security issues in using the first one or both are same?

Thanks :-)

like image 628
Gokul Avatar asked Jul 19 '26 00:07

Gokul


1 Answers

Both ways seems to be fine for me.

For more details, have a look at this rails official guide on security. http://guides.rubyonrails.org/security.html#sql-injection

like image 175
Talha Shoaib Avatar answered Jul 20 '26 16:07

Talha Shoaib