Passing array to Rails where method - sql

So I want to dynamically pass filter parameters to my where method so basically I have this
#colleges = College.where(#filter).order(#sort_by).paginate(:page => params[:page], :per_page => 20)
And the #where is just a string built with this method
def get_filter_parameters
if params[:action] == 'index'
table = 'colleges'
columns = College.column_names
else
table = 'housings'
columns = Housing.column_names
end
filters = params.except(:controller, :action, :id, :sort_by, :order, :page, :college_id)
filter_keys = columns & filters.keys
#filter = ""
first = true
if filter_keys
filter_keys.each do |f|
if first
#filter << "#{table}.#{f} = '#{filters[f]}'"
first = false
else
#filter << " AND #{table}.#{f} = '#{filters[f]}'"
end
end
else
#filter = "1=1"
end
The problem is I don't know how good it is to drop raw SQL into a where method like that. I know normally you can do stuff like :state => 'PA', but how do I do that dynamically?
UPDATE
Okay so I am now passing a hash and have this:
if params[:action] == 'index'
columns = College.column_names
else
columns = Housing.column_names
end
filters = params.except(:controller, :action, :id, :sort_by, :order, :page, :college_id)
filter_keys = columns & filters.keys
#filter = {}
if filter_keys
filter_keys.each do |f|
#filter[f] = filters[f]
end
end
Will that be enough to protect against injection?

in this code here:
College.where(:state => 'PA')
We are actually passing in a hash object. Meaning this is equivalent.
filter = { :state => 'PA' }
College.where(filter)
So you can build this hash object instead of a string:
table = "colleges"
field = "state"
value = "PA"
filter = {}
filter["#{table}.#{field}"] = value
filter["whatever"] = 'omg'
College.where(filter)
However, BE CAREFUL WITH THIS!
Depending on where this info is coming from, you be opening yourself up to SQL injection attacks by putting user provided strings into the fields names of your queries. When used properly, Rails will sanitize the values in your query. However, usually the column names are fixed by the application code and dont need to be sanitized. So you may be bypassing a layer of SQL injection protection by doing it this way.

Related

Filter nil and empty values from an array in rails 3.2

I have a table called Materials and I have created a search form. In the form I want to have select boxes containing the names of the search options. So for example, if you want to search by subject, I want a dropdown with one of each of the subjects. I have code for this that works:
#subject = Material.unscoped.select(:subject).where("materials.subject IS NOT NULL
and materials.subject != '' ").uniq
This gives me what I want with the following form helper:
<%= select_tag "subject", options_from_collection_for_select(#subject, "subject",
"subject"), :include_blank => true, :class => "input_field" %>
BUT - I now want to select only those subjects from Materials that are shared. So I selected the shared Materials using:
#shared = Material.where(:status => 'shared')
And then ran this code:
#subject = #shared.unscoped.select(:subject).where("#shared.subject IS NOT NULL
and #shared.subject != '' ").uniq
Which doesn't work. I assume it's because the sql code can't understand the #shared object. But how to do this?
Note:
I tried using:
#subject = #shared.uniq.pluck(:subject).reject! { |s| s.empty? }
This gives an array of the right fields but then that doesn't work with options_from_collection_for_select.
You can create a scope for the shared query like this:
scope :shared, where(:status => 'shared')
And then you can chain ActiveRecord methods to your liking:
#subject = Material.select(:subject).where("materials.subject IS NOT NULL
AND materials.subject != '' ").shared.uniq
More on scopes here: http://guides.rubyonrails.org/active_record_querying.html#scopes
Try this
#subject = Material.unscoped.select(:subject).where("subject IS NOT NULL and materials.subject != '' and status = 'shared'").uniq

Mongoid dynamic query

This must be an easy one, but I'm stuck...
So I'm using Rails#3 with Mongoid and want to dynamically build query that would depend upon passed parameters and then execute find().
Something like
def select_posts
query = :all # pseudo-code here
if (params.has_key?(:author))
query += where(:author => params[:author]) # this is pseudo-code again
end
if (params.has_key?(:post_date))
query += where(:create_date => params[:post_date]) # stay with me
end
#post_bodies = []
Post.find(query).each do |post| # last one
#post_bodies << post.body
end
respond_to do |format|
format.html
format.json { render :json => #post_bodies }
end
end
You have a few different options to go with here - depending on how complex your actual application is going to get. Using your example directly - you could end up with something like:
query = Post.all
query = query.where(:author => params[:author]) if params.has_key?(:author)
query = query.where(:create_date => params[:post_date]) if params.has_key?(:post_date)
#post_bodies = query.map{|post| post.body}
Which works because queries (Criteria) in Mongoid are chainable.
Alternatively, if you're going to have lots more fields that you wish to leverage, you could do the following:
query = Post.all
fields = {:author => :author, :post_date => :create_date}
fields.each do |params_field, model_field|
query = query.where(model_field => params[params_field]) if params.has_key?(params_field)
end
#post_bodies = query.map{|post| post.body}
And finally, you can take it one level further and properly nest your form parameters, and name the parameters so that they match with your model, so that your params object looks something like this:
params[:post] = {:author => "John Smith", :create_date => "1/1/1970", :another_field => "Lorem ipsum"}
Then you could just do:
#post_bodies = Post.where(params[:post]).map{|post| post.body}
Of course, with that final example, you'd want to sanitize the input fields - to prevent malicious users from tampering with the behaviour.

Ruby on Rails - search in database based on a query

I have a simple form, where I set up a query that I want to browse, for example panasonic viera.
This is on how I search the term in database:
Product.where("name ilike ?", "%#{params[:q]}%").order('price')
The query looks like %panasonic viera%, but I would need to search the query this way: %panasonic%viera% - I need to find all products, where is in the title the word panasonic or viera... but how to make this query?
One solution would be to break up your query into individual terms and build a set of database queries connected by OR.
terms = params[:q].split
query = terms.map { |term| "name like '%#{term}%'" }.join(" OR ")
Product.where(query).order('price')
If you're using PostgreSQL, you can use pg_search gem. It's support full text search, with option any_word:
Setting this attribute to true will perform a search which will return all models containing any word in the search terms.
Example from pg_search:
class Number < ActiveRecord::Base
include PgSearch
pg_search_scope :search_any_word,
:against => :text,
:using => {
:tsearch => {:any_word => true}
}
pg_search_scope :search_all_words,
:against => :text
end
one = Number.create! :text => 'one'
two = Number.create! :text => 'two'
three = Number.create! :text => 'three'
Number.search_any_word('one two three') # => [one, two, three]
Number.search_all_words('one two three') # => []
How about via ARel
def self.search(query)
words = query.split(/\s+/)
table = self.arel_table
predicates = []
words.each do |word|
predicates << table[:name].matches("%#{word}%")
end
if predicates.size > 1
first = predicates.shift
conditions = Arel::Nodes::Grouping.new(predicates.inject(first) {|memo, expr| Arel::Nodes::Or.new(memo, expr)})
else
conditions = predicates.first
end
where(conditions).to_a
end
This isn't working?
WHERE name LIKE "panasonic" OR name LIKE "viera"

XML parsing from API with Nokogiri and Rails 3

Hi Im trying to parse XML from a websites API with Nokogiri. Im just curious to see if Im on the right track. I have a controller wich handles the parsing and then I would like the model to initialize the necessary parameters and then display it as a simple list in the view. I was thinking something like this in the Controller:
def index
doc = Nokogiri::XML(open("http://www.mysomething.com/partner/api/1_0/somerandomkeynumber4b0/channel/11number/material/list/").read)
#news = []
doc.css("news").each do |n|
header = n.css("header").text
source_name = n.css("source_name").text
summary = n.css("summary").text
url = i.css("url").text
created_at = i.css("created_at").text
type_of_media = i.css("type_of_media").text
#news << News.new(
:header => header,)
end
and then the Model:
class News
include ActiveModel::Validations
validates_presence_of :url, :type_of_media
attr_accessor :header, :source_name, :summary, :url, :created_at, :type_of_media
def initialize(attributes = {})
#header = attributes[:header]
#source_name = attributes[:source_name]
#summary = attributes[:summary]
#url = attributes[:url]
#created_at = attributes[:created_at]
#type_of_media = attributes[:type_of_media]
end
Is this how you would do this?! Not sure Im thinking correct on this. Maybe you have any tips on a great way of incorporating Nokogiri with some other thing for the view like Google maps or something. Right now Im getting an error saying
Missing template news/index with {:formats=>[:html], :handlers=>[:builder, :rjs, :erb, :rhtml, :rxml], :locale=>[:en, :en]} in view paths
Thanks in advance!
#noodle: So this:
#news = doc.css('query').map do |n|
h = {}
%w(header source_name summary url created_at type_of_media).each do |key|
h[key.to_sym] = n.css(key).text
end
News.new(h)
end
Is equal to:
#news = []
doc.css("news").each do |n|
header = n.css("header").text
source_name = n.css("source_name").text
summary = n.css("summary").text
url = i.css("url").text
created_at = i.css("created_at").text
type_of_media = i.css("type_of_media").text
#news << News.new(
:header => header,)
end
Did I understand you correctly?! Regarding the template I have located the the problem. It was a minor misspelling. Cheers!
You're really asking two questions here..
Is my xml -> parse -> populate pipeline ok?
Yes, pretty much. As there's no conditional logic in your .each block it would be cleaner to do it like this:
#news = doc.css('query').map do |n|
#...
News.new(:blah => blah, ...)
end
.. but that's a minor point.
EDIT
You could save some typing by initializing a hash from the parsed xml and then passing that to Model.new, like:
#news = doc.css('query').map do |n|
h = {}
h[:header] = n.css('header').text
# ...
News.new(h)
end
EDIT 2
Or even shorter..
#news = doc.css('query').map do |n|
h = {}
%w(header source_name summary url created_at type_of_media).each do |key|
h[key.to_sym] = n.css(key).text
end
News.new(h)
end
In fact #inject could make that shorter still but I think that'd be a little obfuscated.
Why can't rails find my view template?
Dunno, is there one? You've not given enough details to answer that part.

Combining conditions in find. (Rails)

Now i am inputting some data from a form and i have a code to search the database inputting several parameters as input conditions. Now if one the parameters is null (i.e) the field is unchecked i need to replace that parameter with something say * so that the search query is unaffected. How would i do that?
#report = Problem.find(:all, :conditions => ["problems.cause_id = ? and problems.location_id = ? and problems.device_id = ? and problems.priority_id = ?", Report.find_by_id(params[:id]).cause_id, Report.find_by_id(params[:id]).location_id, Report.find_by_id(params[:id]).device_id, Report.find_by_id(params[:id]).priority_id])
It would be better to not have that condition at all than to use *. In this case it's simple as all of your comparison operators are "=". That means you can use the hash form of conditions. Your code is also quite inefficient as you load the same report object 3 or four times. Your question about one of the params being null doesn't make sense for this reason: you just use the same param again and again. Also you set a variable called #report to be a Problem object which is confusing.
#report = Report.find_by_id(params[:id])
conditions = {:cause_id => #report.cause_id, :location_id => #report.location_id, :device_id => #report.device_id, :priority_id => #report.priority_id}
conditions.delete_if{|k,v| v.blank?}
#problem = Problem.find(:all, :conditions => conditions)
rep = Report.find_by_id(params[:id])
cause = rep.cause_id ? rep.cause_id : '*'
location = rep.location_id ? rep.location_id : '*'
device = rep.device_id ? rep.device_id : '*'
priority = rep.priority_id ? rep.priority_id : '*'
#report = Problem.find(:all,
:conditions => ["problems.cause_id = ? and
problems.location_id = ? and
problems.device_id = ? and
problems.priority_id = ?",
cause, location,
device, priority
]
)