I'm trying to write a query with LIKE and = conditions:
Model.where("extract(day from month) = ? OR lower(name) LIKE ?",params[:filter], "%#{params[:filter]}%".downcase )
I get return for the month value but i don't get any return for the name value.
so how can i use 'LIKE' and 'EQUAL TO' together in one query?
[EDIT] : when i use only the like statement it works fine.
We can definitely use like and equal to in the same query. Your query looks correct. Please check with hardcoded values to double check ex: Model.where("lower(name) LIKE ?", "%aManda%".downcase ) and then same for both conditions together.
Related
Hi im fetching the user input and displaying the records that matches the condition, my query will look like
customers = customers.where('customers.contact_num ilike :search', {search: "%#{options[:search_contact]}%"})
here in db the contact number is stored in string with the format (091)-234-5678 like that
on while searching the user on basis of contact number if i search like this
091 it filters the number correctly, but while searching like 0912, it doesn't display record due to the braces, so how to modify the query to neglect the ) and - while searching..
As im new to the domain please help me out
thanks in advance
What about using REGEXP_REPLACE to remove all non-digit chars from the search - something like below?
customers = customers.where("REGEXP_REPLACE(customers.contact_num,'[^[:digit:]]','','g') ilike :search", {search: "%#{options[:search_contact]}%"})
Changing the query is hard. Let's not do that.
Instead right a quick script to transforms your numbers into
1112223333 form. No formatting at all. Something like:
require 'set';
phone = "(234)-333-2323"
numbers = Set.new(["1","2","3","4","5","6","7","8","9","0"])
output = phone.chars().select{|n| numbers.include?(n)}.join("")
puts output
=> "2343332323"
Then write a little function to transform them into display form for use in the views.
This will make your query work as is.
I have a model with a string attribute, the attribute can have values 'abc', 'def', 'ghi' or 'jkl' + count I need to get all records with the value 'jkl' + count. I was hoping something like:
Model.where(status[0..2]: 'jkl')
Would work, but it seems like it doesn't, is there a good way for me to do this?
You can use LIKE query with wildcards
Model.where('status LIKE ?', 'ijk%')
So let's say i have a Customer model with array column phones.
It's pretty easy to find all customers with given phone
Customer.where('? = ANY(phones)', '+79851234567')
But i can't figure out how to use LIKE with wildcard when i want to find customers with phones similar to given one, something like:
Customer.where('ANY(phones) LIKE ?', '+7985%')
I'm using PostgreSQL 9.5 and Rais 4.2
Any ideas?
I think, first of all, its better to use second table phones with fields customer_id, phone_number. I think it's more rails way ). In this way you can use this query
Phone.where("phone_number LIKE ?", '%PART%').first.customer
If you serialize your array in some text field, by example JSON, you should use % on both sides of your pattern:
Customer.where('phones LIKE ?', '%+7985%')
If you have an array in your database, you should use unnest() function to expand an array to a set of rows.
Can you try this
Customer.where("array_to_string(phones, ', ') like ?", '+7985%')
I believe this will work.
Just usuing SQLlite3 can I find the values that are LIKE what I am looking for and pass in an array?
e.g. I'd like something of the sort
Url.where("token LIKE ?" ["_bc","a_b","ab_"])
No. You'll have to repeat the LIKE clauses for each of the condition, something like this:
like_conditions = %w(_bc a_b ab_)
Url.where((["token LIKE ?"] * like_conditions).join(" OR "), *like_conditions)
# => SELECT `urls`.* FROM `urls` WHERE (token like '_bc' OR token like 'a_b' OR token like 'ab_')
The first part of the where clause constructs an array of token LIKE ? strings with the same length as the number of like conditions and joins them using OR (change this to ANDs if you need an ANDed query instead).
The last part just passes the conditions but not as an array but as the individual elements instead (that's what the * does) because the query now has three parameters instead of one.
You could try somehting like this (untested for SQLite):
class Url < ActiveRecord::Base
scope :with_tokens, lambda{|*tokens|
query = tokens.length.times.map{"token LIKE ?"}.join(" OR ")
where(query, *tokens)
}
end
Url.with_tokens("_bc", "a_b", "ab_")
In my app I have invoice numbers like this:
2014.DEV.0001
2014.DEV.0002
2014.TSZ.0003
The three character code is a company code. When a new invoice number needs to be assigned it should look for the last used invoice number for that specific company code and add one to it.
I know the company code, I use a LIKE to search on a partial invoice number like this:
last = Invoice.where("invoice_nr LIKE ?", "#{DateTime.now.year}.#{company_short}.").last
This results in this SQL query:
SELECT "invoices".* FROM "invoices" WHERE "invoices"."account_id" = 1 AND (invoice_nr LIKE '2014.TSZ.') ORDER BY "invoices"."id" DESC LIMIT 1
But unfortunately it doesn't return any results. Any idea to improve this, as searching with LIKE doesn't seem to be correct?
Try wrapping string with % and use lower to convert the query string and result into downcase to avoid any wrong results due to case, try this
last = Invoice.where("lower(invoice_nr) LIKE lower(?)", "%#{DateTime.now.year}.#{company_short}.%").last
You want % for partial match
last = Invoice.where("invoice_nr LIKE ?", "%#{DateTime.now.year}.#{company_short}.%").last
Since you want to match only the left part you need to add one % at the right part of your string
Invoice.where("invoice_nr LIKE ?", "#{DateTime.now.year}.#{company_short}.%").last