Rails search method - mysql

I have tried using sql to write a simple search method, I have so far written this;
User.where("username LIKE '#{input}'")
the input variable is 'adam', however I don't want to find the username's that are equal to 'adam' I want to find usernames that include 'adam' or include the letter 'a' etc.... I was wondering how I would go about doing that? I am not very familiar with sql queries.
Thanks

You can use this:
User.where("username LIKE '%#{input}%'")
OR
User.where("username like ?","%name%")

If you create method then go to model page & then follow this structure like below:
def self.username(username)
if username
where("username LIKE ?", "%#{username}%")
else
all
end
end
Or create only controller like below:
User.where(["username LIKE ? ", "%#{params[:username]}%"])
I think will help you

Related

Can i use question mark in MySQL this way

i'm using node.js to build a web. I connect to my database (Mysql) and
get the data then return to the client side.
I know that i can use the literal template to write my sql expression like below
promise(`SELECT table.name FROM table WHERE name = ?`,[parameter])
and i'm would like to know can i write my sql expression like this?
promise(`SELECT table.? FROM table`,[parameter])
I know the result is different, i just want to know it is right or not.
thank you and have a nice day.
No, but you could use string interpolation like:
promise(`SELECT table.name FROM table WHERE name = ${parameter}`)

Rails SQL QUERY Like

I've some problem with an SQL Query
I've users which have skills
def skills=(value)
super(value.reject(&:blank?).join("|")) if !value.nil?
end
def skills
super.present? ? super.split("|") : []
end
Here is my problem. When I query on this field with "like", word order matter. How can I avoid that ?
User.where("skills LIKE '%car%driving_license%'")
Each user with skills which at least contain car and driving_license
User.where("skills LIKE '%driving_license%car%'")
Each user with skills which at least contain car and driving_license but in a different order
I want to be able to avoid this order problem. Any help ?
If you sort the skills you can know the order and assemble a like query that will match both of them. You can create a migration to sort the existing skills.
def skills=(value)
super(value.reject(&:blank?).sort.join("|")) if value
end
rails g migration sortUserSkills
User.where.not(skills: nil).each do u
u.skills = u.skills
u.save
end
LIKE + OR queries are tough if my memory serves me. You can try ARel, but I think you lose LIKE.
2 things I can think of:
Do the queries separately and combine results.
Use something like this which may not work:
conditions = ['%driving_license%car%', '%car%driving_license%']
User.where("skills LIKE ?", conditions)

Performing rails query with mysql with backslash in string

I have a database entry that looks like the following:
name = servername\vs1
We have a search that is looking for this term.
scope :search, ->(term) {
if term
where('name LIKE ?', "%#{term}%")
else
all
end
}
However, it isn't finding it. When someone searches for severname, of course, it shows up. But when they include the backslash it isn't found.
After doing some research, I found that rails is currently adding a single backslash to the query term prior to search (servername\\vs1) but mysql needs the following format: (servername\\\\vs1).
So, I was hoping there was an easy rails way to add additional backslashes. Looking for any good solution.
Thanks
Easiest to use Arel, like this:
scope :search, ->(term){
t = arel_table
term ? where( t[:name].matches("%#{term}%") )
: all
}
Example:
Simple.search('\a').to_sql
"SELECT \"simples\".* FROM \"posts\" WHERE (\"simples\".\"title\" LIKE '%\\a%')"

Creating an OR statement using existing conditions hash

I am working on a problem where I need to add an OR clause to a set of existing conditions. The current conditions are built in a hash in a method and at the end, they are used in the where clause. Here is a simplified example:
...
conds.merge!({:users => {:archived => false}})
Model.where(conds)
I am trying to add an OR clause to the current set of conditions so it would be something like '(conditions) OR new_condition'. I'd like to add the OR statement without converting each addition to the conds hash into a string. That would be my last option. I was hoping someone has done something like this before (without using Arel). I seem to recall in Rails 2 there was a way to parse a conditions hash using a method from the model (something like Model.some_method(conds) would produce the where clause string. Maybe that would be a good option to just add the OR clause on to that string. Any ideas are appreciated. Thank you for your help!
I found a way to do what I needed. Instead of changing all of the conditions that I am building, I am parsing the conditions to SQL using sanitize_sql_for_conditions. This is a private method in ActiveRecord, so I had to put a method on the model to allow me to access it. Here is my model method:
def self.convert_conditions_hash_to_sql(conditions)
self.sanitize_sql_for_conditions(conditions)
end
So, once I convert my conditions to text, I can add my OR clause (along with the appropriate parentheses) to the end of the original conditions. So, it would go something like this:
Model.where('(?) OR (model.type = ? AND model.id IN(?))', Model.convert_conditions_hash_to_sql(conds), model_type, model_id_array)

What is the "Rails Way" of doing a query with an OR clause using ActiveRecord?

I'm using Rails 3 with a MySQL database, and I need to programmatically create a query like this:
select * from table where category_name like '%category_name_1%'
OR category_name like '%category_name_2%'
(...snip...)
OR category_name like '%category_name_n%'
Given the table size and the project scope (500 rows at most, I think), I feel that using something like thinking sphinx would be overkill.
I know I could simply do this by writing the query string directly, but wanted to know if there's an ActiveRecord way to do this. There's no mention of this on the official guide, and I've been googling for a long while now, just to end empty-handed :(
Also, is there a reason (maybe a Rails reason?) to not to include the OR clause?
Thanks!
Assuming you have an array names with category names:
Model.where( names.map{"category_name LIKE ?"}.join(" OR "),
*names.map{|n| "%#{n}%" } )
you should google first, there is already an answer.
Look here and then here
and you'll get something like this:
accounts = Account.arel_table
Account.where(accounts[:name].matches("%#{user_name}%").or(accounts[:name].matches("%#{user_name2}%")))
If you look at the guide, they have examples that can easily be modified to this:
Client.where("orders_count = ? OR locked = ?", params[:orders], false)
Mysql has a regexp function now that can clean things up a bit, assuming there's no regex metachars in your category names:
Table.where "category_name regexp '#{names.join('|')}'"