Combine arrays of conditions in Rails - ruby-on-rails

I'm using the Rails3 beta, will_paginate gem, and the geokit gem & plugin.
As the geokit-rails plugin, doesn't seem to support Rails3 scopes (including the :origin symbol is the issue), I need to use the .find syntax.
In lieu of scopes, I need to combine two sets of criteria in array format:
I have a default condition:
conditions = ["invoices.cancelled = ? AND invoices.paid = ?", false, false]
I may need to add one of the following conditions to the default condition, depending on a UI selection:
#aged 0
lambda {["created_at IS NULL OR created_at < ?", Date.today + 30.days]}
#aged 30
lambda {["created_at >= ? AND created_at < ?", Date.today + 30.days, Date.today + 60.days]}
#aged > 90
lamdba {["created_at >= ?", Date.today + 90.days]}
The resulting query resembles:
#invoices = Invoice.find(
:all,
:conditions => conditions,
:origin => ll #current_user's lat/lng pair
).paginate(:per_page => #per_page, :page => params[:page])
Questions:
Is there an easy way to combine these two arrays of conditions (if I've worded that correctly)
While it isn't contributing to the problem, is there a DRYer way to create these aging buckets?
Is there a way to use Rails3 scopes with the geokit-rails plugin that will work?
Thanks for your time.

Try this:
ca = [["invoices.cancelled = ? AND invoices.paid = ?", false, false]]
ca << ["created_at IS NULL OR created_at < ?",
Date.today + 30.days] if aged == 0
ca << ["created_at >= ? AND created_at < ?",
Date.today + 30.days, Date.today + 60.days] if aged == 30
ca << ["created_at >= ?", Date.today + 90.days] if aged > 30
condition = [ca.map{|c| c[0] }.join(" AND "), *ca.map{|c| c[1..-1] }.flatten]
Edit Approach 2
Monkey patch the Array class. Create a file called monkey_patch.rb in config/initializers directory.
class Array
def where(*args)
sql = args[0]
unless (sql.is_a?(String) and sql.present?)
return self
end
self[0] = self[0].present? ? " #{self[0]} AND #{sql} " : sql
self.concat(args[1..-1])
end
end
Now you can do this:
cond = []
cond.where("id = ?", params[id]) if params[id].present?
cond.where("state IN (?)", states) unless states.empty?
User.all(:conditions => cond)

I think a better way is to use Anonymous scopes.
Check it out here:
http://railscasts.com/episodes/112-anonymous-scopes

Related

Get impresions count from today, yesterday and this month, Impresionist gem

I am using gem called impressionist to log page views on show action.
Everythink works just great.I can get number of all pageviews with:
#advertisement.impression_count
But now I want to be able filter pageviews per today, yesterday and this month.
So far I came up with this solution.
#today = Impression.where( :conditions => { :created_at => Date.today...Date.today+1 }, :impresionable_id =>#advertisement.id)
There is no errors.
Then In view:
<%= "#{#today} views so far!" %>
gives me #<Impression::ActiveRecord_Relation:0x000000068d46f8>
then I tried to add like : <%= "#{#today.impression_count} views so far!" %> gives me this :
undefined method `impression_count'
then I tried just :<%= "#{#today.count} views so far!" %> and still error:
Mysql2::Error: Unknown column 'conditions.created_at' in 'where clause': SELECT COUNT(*) FROM `impressions` WHERE (`conditions`.`created_at` >= '2014-12-18' AND `conditions`.`created_at` < '2014-12-19') AND `impressions`.`impresionable_id` = 127
Any ideas ?
Thanks in advance!
#today = Impression.where( :conditions => { :created_at => Date.today...Date.today+1 }, :impresionable_id =>#advertisement.id)
returns a #<Impression::ActiveRecord_Relation:0x000000068d46f8>.
Try this:
#today = Impression.where(created_at: Date.today...Date.today+1, impresionable_id: #advertisement.id).count
Add scopes in impression.rb
scope :today, -> {where("created_at >= ? AND created_at < ?", Time.now.beginning_of_day, Time.now.end_of_day)}
scope :yesterday, -> {where("created_at >= ? AND created_at < ?", 1.day.ago.beginning_of_day, 1.day.ago.end_of_day)}
scope :this_month, -> {where("created_at >= ? AND created_at < ?", Time.now.beginning_of_month, Time.now.end_of_month)}
in Controller:
#today = Impression.today.where(impresionable_id: #advertisement.id)
#yesterday = Impression.yesterday.where(impresionable_id: #advertisement.id)
#this_month = Impression.this_month.where(impresionable_id: #advertisement.id)
And you can use these scopes anywhere you need to filter Impressions by date today, yesterday or this month. It's better compared to writing the where clause everywhere.
There's no need for the conditions hash.
today = Date.today
range = today..today.next_day
#imp = Impression.where(created_at: range, impressionable_id: #advertisement.id)
And if an #advertisement can have impressions, then the following would be better:
#imp = #advertisement.impressions.where(created_at: range)
Then to get the count, you must:
#today = #imp.count
Also, just FYI, you might need to use DateTime.now instead of Date.today because you're comparing with a datetime field i.e. created_at.
It was easier than I though
In advertisement.rb
has_many :impressions, :as=>:impressionable
def view_count_yesterday
impressions.where("created_at >= ? AND created_at < ?", 1.day.ago.beginning_of_day, 1.day.ago.end_of_day).size
end
def view_count_today
impressions.where("created_at >= ? AND created_at < ?", Time.now.beginning_of_day, Time.now.end_of_day).size
# impressionist_count(:start_date => 1.day.ago)
end

Rails 3 Query - IN (?) can be blank

This query won't return any records, when hidden_episodes_ids is empty.
:conditions => ["episodes.show_id in (?) AND air_date >= ? AND air_date <= ? AND episodes.id NOT IN (?)", #show_ids, #start_day, #end_day, hidden_episodes_ids]
If it's empty, the SQL will look like NOT IN (null)
So my solution is:
if hidden_episodes_ids.any?
*mode code*:conditions => ["episodes.show_id in (?) AND air_date >= ? AND air_date <= ? AND episodes.id NOT IN (?)", #show_ids, #start_day, #end_day, hidden_episodes_ids]
else
*mode code*:conditions => ["episodes.show_id in (?) AND air_date >= ? AND air_date <= ?", #show_ids, #start_day, #end_day]
end
But it is rather ugly (My real query is actually 5 lines, with joins and selects etc..)
Is there a way to use a single query and avoid the NOT IN (null)?
PS: These are old queries migrated into Rails 3, hence the :conditions
You should just use the where method instead as that'll help clean all of this up. You just chain it together:
scope = Thing.where(:episodes => { :show_id => #show_ids })
scope = scope.where('air_date BETWEEN ? AND ?', #start_day, #end_day)
if (hidden_episode_ids.any?)
scope = scope.where('episodes.id NOT IN (?)', hidden_episode_ids)
end
Being able to conditionally modify the scope avoids a lot of duplication.

Active Record Query Using Associated Model in Find Clause

I'm having a blonde moment and probably a brain freeze.
In my rails3 app, I have users and tasks. My users have many tasks...
I have due and overdue tasks as follows:
#due = Task.find(:all, :conditions => ["dueddate >= ? AND AND status = ?", Date.today, false], :include => :taskcategories, :order => "dueddate asc")
What I want to do in my tasks view, is list the users with due tasks...
For some reason, I can't get my head around it. I have tried this, but it's not working:
#task = Task.all
#user = User.find(:all, :conditions => ["#task.dueddate <= ? AND
#task.status = ?", Date.today + 7.days, false])
I'm sure this is easy, can anyone help me!!?
I guess this should work
updated
User.joins(:tasks)
.where("tasks.dueddate <= ? AND tasks.status = ?", Date.today + 7.days, false).group(:id)
This should work with SQLite and MySQL. However, PostgreSQL requires that you supply all the columns of the table. If it's a small table, you could simply type the names. Or you could add this method to the model:
def self.column_list
self.column_names.collect { |c| "#{self.to_s.pluralize.downcase}.#{c}"}.join(",")
end
and change .group(:id) to .group(User.column_list)

Rails 3: sql injection free queries

I love new Rail 3!
The new query syntax is so awesome:
users = User.where(:name => 'Bob', :last_name => 'Brown')
But when we need to do something like
SELECT * FROM Users WHERE Age >= const AND Money > const2
We have to use
users = User.where('Age >= ? and money > ?', const, const2)
Which is not very cool. The following query is not safe because of SQL injection:
users = User.where('Age >= #{const} and money > #{const2}')
I like the C#/LINQ version
var users = DB.Where(u => u.Age >= const && u.Money > const2);
Is there a way to do something like that in Rails?
The new querying with rails isn't vulnerable to SQL injection. Any quotes in the argument are escaped.
Rails 3 AR has gained the delayed execution that LINQ has had for a while. This lets you chain any of the query methods. The only time you have to put 2 or more parts into a where is when you want an OR.
That aside, there are many different ways to do your query.
Users.where('age >= ?', age).where('money > ?', money)
Users.where('age >= ? and money > ?', age, money)
class User < ActiveRecord::Base
scope :aged, lambda { |age| where('age >= ?', age) }
scope :enough_money, lambda { |money| where('money > ?', money) }
scope :can_admit, lambda { |age, money| aged(age).enough_money(money) }
end
Users.aged(18).enough_money(200)
Users.can_admit(18, 200)
You might be interested in MetaWhere with which you can write:
users = User.where(:age >= const, :money > const2)
In Rails 3 you can chain these selections together. I'm not up on the specific syntax, but this is a good start: http://railscasts.com/episodes/202-active-record-queries-in-rails-3
The basic concept is that you can chain together scopes or where clauses, etc:
meta-code here:
users = User.where(:age_of_consent).where(:has_credit)
scope :age_of_consent where("age >= ?", 18)
scope :has_credit where("credit > ?", 10)
You can pass a hash of named parameters to your query which is an improvement over the anonymous positional parameters.
users = User.where('Age >= ? and money > ?', const, const2)
becomes (is is more similar to the LINQ syntax)
users = User.where('Age >= :const and money > :const2', {:const => const, :const2 => const2})

Use the same parameters many times in a find conditions: hash

I have a model who holds 2 properties: valid_from and valid_to.
I need to select all instances that are currently valid, i.e. valid_from <= today and valid_to >= today.
i have the following find :
Mymodel.find(:all, :conditions => ["valid_from <= ? and valid_to >= ?", Date.today, Date.today])
I already thought about storing Date.today in a variable and calling that variable, but i still need to call it twice.
my_date = Date.today
Mymodel.find(:all, :conditions => ["valid_from <= ? and valid_to >= ?", my_date, my_date])
Is there a way to improve and do only one call to the variable to match all the "?" in the :conditions ?
thanks,
P.
I would use named_scope. In model add:
named_scope :valid,
:conditions =>
["valid_from <= ? and valid_to >= ?", Date.today, Date.today]
And then in your controller you can call:
#mymodels = Mymodel.valid
I think that focusing on reducing two calls to Date.today to only one call is wasting of time. It won't make your application faster or using less memory.
I'm not aware of a way to do what you're asking, but even if you could I don't think it would buy you much. I would create a named scope within your model class.
In this example, you can pass the date to the named scope, or it will default to today's date if no date is specified:
named_scope :by_valid_date, lambda { |*args|
{ :conditions => ["valid_from <= ? and valid_to >= ?",
(args.first || Date.today), (args.first || Date.today)]} }

Resources