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%')"
Related
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
I'm using Rails with ActiveAdmin gem. And I want to select some information from mysql database.
sql = ActiveRecord::Base.connection();
s="SELECT word FROM dics WHERE word LIKE 'tung%'";
ten = sql.execute(s);
But when I printed out "ten" to screen, it showed that:
#<Mysql2::Result:0x4936260>
How can I get the information of records?
I suggest that you don't use ActiveRecord::Base.connection directly. Sticking with ARel syntax should work for most cases, and your example doesn't seem like an edge case.
As stated in the comments above, try the following:
dics = Dic.select(:word).where(["word LIKE ?", "tung%"]).all
In order to pluck some special field of object, not objects themselves, use pluck instead of all:
# instead of .pluck(:word) use real field identifier
dics = Dic.where(["word LIKE ?", "tung%"]).pluck(:word)
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('|')}'"
I'm trying to accomplish a multiple word searching in a quotes database using Ruby, ActiveRecord, and MySQL. The way I did is shown bellow, and it is working, but I would like to know if there a better way to do.
# receives a string, splits it in a array of words, create the 'conditions'
# query, and send it to ActiveRecord
def search
query = params[:query].strip.split if params[:query]
like = "quote LIKE "
conditions = ""
query.each do |word|
conditions += (like + "'%#{word}%'")
conditions += " AND " unless query.last == word
end
#quotes = Quote.all(:conditions => conditions)
end
I would like to know if there is better way to compose this 'conditions' string. I also tried it using string interpolation, e.g., using the * operator, but ended up needing more string processing. Thanks in advance
First, I strongly encourage you to move Model's logic into Models. Instead of creating the search logic into the Controller, create a #search method into your Quote mode.
class Quote
def self.search(query)
...
end
end
and your controller becomes
# receives a string, splits it in a array of words, create the 'conditions'
# query, and send it to ActiveRecord
def search
#quotes = Quote.search(params[:query])
end
Now, back to the original problem. Your existing search logic does a very bad mistake: it directly interpolates value opening your code to SQL injection. Assuming you use Rails 3 you can take advantage of the new #where syntax.
class Quote
def self.search(query)
words = query.to_s.strip.split
words.inject(scoped) do |combined_scope, word|
combined_scope.where("quote LIKE ?", "%#{word}%")
end
end
end
It's a little bit of advanced topic. I you want to understand what the combined_scope + inject does, I recommend you to read the article The Skinny on Scopes.
MySQL fulltext search not working, so best way to do this:
class Quote
def self.search_by_quote(query)
words = query.to_s.strip.split
words.map! { |word| "quote LIKE '%#{word}%'" }
sql = words.join(" AND ")
self.where(sql)
end
end
The better way to do it would be to implement full text searching. You can do this in MySQL but I would highly recommend Solr. There are many resources online for implementing Solr within rails but I would recommend Sunspot as an entrance point.
Create a FULLTEXT index in MySQL. With that, you can leave string processing to MySQL.
Example : http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
I've been following the Railscast for adding searching, sorting, and pagination to my app. I've modified my search logic in the model to search to columns (description and title). This seems to be working. I've also changed it to search non case sensitive. This seems to work perfect in my local app, but when I push it to heroku, I can only search by lowercase. Search with any capital letters at all produces no results, even if the case matches the results.
here is the code in my model:
def self.search(search)
if search
where('LOWER (description) LIKE ? OR LOWER (title) LIKE ?', "%#{search}%" , "%#{search}%")
else
scoped
end
end
Try
where("LOWER (description) LIKE ? OR LOWER (title) LIKE ?", "%#{search.downcase}%" , "%#{search.downcase}%")
I had this problem, too. Heroku uses PostgreSQL and the LIKE-Operator there is strongly typed to strings. Check this http://www.postgresql.org/docs/8.3/interactive/functions-matching.html