How to search for wild card in Rails - ruby-on-rails

Im trying to search my User model for all Users that start with any integer, I have code for individual letters and it works, but Im having trouble getting it working with a wild card. Right now I have this code:
in my view:
<%= link_to '#', users_charlist_path(:char => '[0123456789]' %>
and in my controller I have:
def charlist
#a = User.where('goal like ?', "#{params[:char]}%").to_a
end
how ever, '[0123456789]', doesnt seem to work as it does not return anythign to me even though I have users whose names begin with an integer. how do i do this?

The where method is a part of ActiveRecord which maps the objects to the database. So how you can query the database with a regex depends on which db you are using not on ruby. You need to look up the regex functions of the database your using. For mysql you can find them here:
http://dev.mysql.com/doc/refman/5.1/de/regexp.html
An alternative is to select all objects an use the select method to filter the results that match your needs. That method is documented here:
http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-select
On big amounts of data I whould suggest to use the database even if that means your application isnt 100% portable between different database systems.

Related

Searching in polygons in sphinx using Thinking Sphinx

I have setup thinking sphinx for real-time indexing and It works very well and search with geodist as well.But now I want to search the records within polygon.
Sphinx documentation explains it very well at Geo-distance searching
now I want to use this functionality using thinking sphinx.
Thinking sphinx does explain about geodist search Here
But It does not state how to search within a polygon.
Can any one help me here to do that?
Thinking Sphinx doesn't have anything inbuilt to provide a neat interface for the polygon searching, but it's certainly possible to use the functionality.
You'll want to generate the SphinxQL SELECT clause that you'd like, filter on it accordingly, and/or you can access your custom attributes using the AttributesPane. The following code is hopefully clear:
search = Model.search("foo",
:select => "*, CONTAINS(GEOPOLY2D(...), ...) AS inside",
:with => {:inside => true}
); ""
search.context[:panes] << ThinkingSphinx::Panes::AttributesPane
search.collect { |instance| instance.sphinx_attributes["inside"] }
The ; "" at the end of the first statement is only needed when running this in IRB or a Rails console - you want to avoid calling search in a way that evaluates the results until you've added the pane in. Search results are normally lazily loaded, but IRB calls inspect to print statement results which removes the lazy advantage.
Panes are discussed in a blog post I wrote, and the source code for the AttributesPane class is very simple. You may also want to write a custom middleware class that uses your own options and translates them into the polygon functions - the Geographer class (which is what translates :geo into GEODIST) is a good reference for that.

Complex search screens in Rails 3

I need to implement some search functionality within a Rails application. Most of the stuff I have found is generally aimed at simple plain-text search. I am trying to implement something much more specific. The sort of functionality I am looking to create is this (from a C application):
http://andyc.ac/query.gif
The form just submits the data entered by the user. So I need to translate strings like "3..7" into SQL conditions for the where method e.g.
TestLine.where( "test_int >= ? and test_int <= ?", MinInt, MaxInt )
It seems like this is something that already exists somewhere. The exact format expected is not too important, as the users are not shared between the Rails and C applications. How would this be done?
FWIW the specific functionality you describe is actually supported directly. Well.. almost. From the docs:
A range may be used in the hash to use the SQL BETWEEN operator:
Student.where(:grade => 9..12)
Of course then it's a matter of translating the user's string input to a Range, which isn't very complex, e.g.:
def str_to_range str
str =~ /(\d+)\.\.(\d+)/
Range.new *$~.captures.map(&:to_i)
end
It would probably make the most sense in a scope on your model. (Of course a shortcut would be to simply eval '9..12' but evaling input from the end user is a really, really bad idea.)
Give a look at thinking sphinx(http://freelancing-god.github.com/ts/en/). It might make your task a lot easier. You can search in that:
http://freelancing-god.github.com/ts/en/searching.html#basic

Ruby on Rails build query in pieces

There was a very similar question before but i still struggle.
Is it possible to build a query up in stages?
Let's say I have a search form with many text and select fields that may be chained with and/or or which could be blank.
So the sql statement should consist of several parts that are connected individually for each search.
I tried to create strings for every option and put them to a symbol? (i mean #options) and put that in the where clause (e.g. Product.where(#options) ). That works somehow but i have got troubles with this part: 'params[:query]' when it's in quotes. Either my sql statement says 'select products from products where (name like params[:query]') or if i try #{params[:query]} it says: select products from products (where 'name' like ''.)
So how can i chain different parts of a query?
I looking forward to your answers!
Never, ever, ever embed raw strings in your SQL. This is extremely bad form. You should always use the escaping mechanism provided by Rails or something equivalent to avoid ending up in serious trouble. Inserting content from params is very dangerous and should never be done as it only takes this to nuke your app: { :query => '\"-- DROP TABLE users;' }
Generally you use the helper methods provided by ActiveRecord to build up your query in stages:
scope = Product
if (params[:query].present?)
scope = scope.where([ 'name LIKE ?', "%#{params[:query]}%" ])
end
if (params[:example].present?)
scope = scope.where(:example => true)
end
#products = scope.all
You can build it up in stages like this, modifying the scope in-place each time, and then execute the final call to retrieve it. Generally that's when you use your paginator to split up the results.
It's okay to put pretty much anything in your options because it should be escaped by the time it hits the SQL phase, much as anything on the HTML side is escaped for you as well.
Don't confuse instance variables like #options with a symbol like :query. The two are very different things. Instance variables have the benefit of propagating to your view automatically, so they are often used extensively in controllers. Views should avoid modifying them whenever possible as a matter of style.

Is this Rails 3 search vulnerable to SQL injection?

Suppose I've got a search box on a page in a Rails 3 app where you can search for a client by business name or city. In my controller's index method I do this:
if params[:search]
#clients = Client.where("clients.business_name LIKE :business_name OR clients.city = :city", :business_name => "%#{params[:search]}%", :city => params[:search])
Those hash values get substituted into the SQL and surrounded in quotes. If my input into the search box includes quotes or other dangerous characters, I'll see them being escaped in the development log, like:
...WHERE (clients.business_name LIKE '%Something\' DROP TABLE Foo%'...
Or
...WHERE... OR clients.city = 'Something OR 1=1')
So, since the OR 1=1 is inside the quotes Rails adds, it just produces no match for the city name, and since the quote in the DROP TABLE attempt is escaped, it also produces no match for the business name.
This isn't using actual prepared statements, where the query is sent to the database first without the search values filled in, then subsequently, the search values are sent to the database to fill in. I thought that was the safest approach, but Rails doesn't do it; I think this is because it's not available in all databases and implementations vary.
Is this open to SQL injection in some way? I don't see it, but again, it's not using prepared statements, so I wonder. If there's a vulnerability, how could I do this more safely?
No, there's not a SQL injection vulnerability here. ActiveRecord will call connection.quote on the values of the hash that you passed in as the second parameter to where, so you are safe.
The only potential SQL injection point I could think of would be if there were some undiscovered bug in connection.quote, which is pretty unlikely.

Rails optmization (with activerecord and view helpers)

Is there a way to do this in Rails:
I have an activerecord query
#posts = Post.find_by_id(10)
Anytime the query is called, SQL is generated and executed at the DB that looks like this
SELECT * FROM 'posts' WHERE id = 10
This happens every time the AR query is executed. Similarly with a helper method like this
<%= f.textarea :name => 'foo' %>
#=> <input type='textarea' name='foo' />
I write some Railsy code that generates some text that is used by some other system (database, web browser). I'm wondering if there's a way to write an AR query or a helper method call that generates the text in the file. This way the text rendering is only done once (each time the code changes) instead of each time the method is called?
Look at the line, it may be going to the database for the first one but ones after it could be saying CACHE at the start of the line meaning it's going to ActiveRecord's query cache.
It also sounds to me like you want to cache the page, not the query. And even if it were the query, I don't think it's as simple as find_by_id(10) :)
Like Radar suggested you should probably look into Rails caching. You can start with something simple like the memory store or file cache and then move to something better like memcached if necessary. You can throw in some caching into the helper method which will cache the result after it is queried once. So for example you can do:
id = 10 # id is probably coming in as a param/argument
cache_key = "Post/#{id}"
#post = Rails.cache.read(cache_key)
if #post.nil?
#post = Post.find_by_id(id)
# Write back to the cache for the next time
Rails.cache.write(cache_key,#post)
end
The only other thing left to do is put in some code to expire the cache entry if the post changes. For that take a look at using "Sweepers" in Rails. Alternatively you can look at some of the caching gems like Cache-fu and Cached-model.
I'm not sure I understand your question fully.
If you're asking about the generated query, you can just do find_by_sql and write your own SQL if you don't want to use the active record dynamic methods.
If you're asking about caching the resulset to a file, it's already in the database, I don't know that if it was in a file it would be much more efficient.

Resources