Arel is a quite powerful SQL AST manager that lets you appropriately combine selection statements for simple to very complicated queries.
Arel is a library that was introduced in Rails 3 for use in constructing SQL queries. Every time you pass a hash to where, it goes through Arel eventually. Rails exposes this with a public API that we can hook into when we need to build a more complex query.
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Arel is a SQL AST manager for Ruby. It. simplifies the generation of complex SQL queries, and. adapts to various RDBMSes.
This is how you perform a like query in arel:
users = User.arel_table
User.where(users[:name].matches("%#{user_name}%"))
PS:
users = User.arel_table
query_string = "%#{params[query]}%"
param_matches_string = ->(param){
users[param].matches(query_string)
}
User.where(param_matches_string.(:name)\
.or(param_matches_string.(:description)))
Try
User.where("name like ?", "%#{params[:query]}%").to_sql
PS.
q = "%#{params[:query]}%"
User.where("name like ? or description like ?", q, q).to_sql
Aaand it's been a long time but @cgg5207 added a modification (mostly useful if you're going to search long-named or multiple long-named parameters or you're too lazy to type)
q = "%#{params[:query]}%"
User.where("name like :q or description like :q", :q => q).to_sql
or
User.where("name like :q or description like :q", :q => "%#{params[:query]}%").to_sql
Reuben Mallaby's answer can be shortened further to use parameter bindings:
User.where("name like :kw or description like :kw", :kw=>"%#{params[:query]}%").to_sql
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With