Adding more than one string to a controller find condition? - ruby-on-rails-3

I have the following code in one of my Rails (3.1) controllers:
#count = Call.where(:destination => current_user.destination_id).count
#count_day = Call.where('created_at > ?', 1.days.ago).count
#count_month = Call.where('created_at > ?', 30.days.ago).count
They are all working as expected, but I am trying to somehow merge two of them together so it shows the count of calls created in the last 1 day, but only for calls with a destination that matches the current users destination_id value.
I have tried to add :condition but with no joy:
#count_day = Call.where(:destination => current_user.destination_id, :condition ['created_at > ?', 1.days.ago]).count
Is it possible to add more than one condition in this way? If so, how?

Try this:
#count_day = Call.where("destination = :destination AND created_at > :date", { :destination => current_user.destination_id, :date => 1.days.ago}).count

Where creates a scope and scopes can be chained, so you can do
Call.where(:destination =>current_user.id).where("created_at > ?", 1.day.ago).count

Related

is there any way that can offset from specific record when using scope

i have a lot of methods that look for records after specific active record. examples are:
def photo_recent
offsetphoto = Photo.find(params[:id])
#photos = Photo.recent.where('created_at> ?', offsetphoto.id).limit(10)#recent is a scope using created_at
end
def photo_recent
offsetphoto = Photo.find(params[:id])
#photos = Photo.popular.where('like_count > ?', offsetphoto.like_count).limit(10)#popular is a scope using like_count
end
i was wondering if there is any way to modularize this such as:
#photos = Photo.recent.offset(Photo.find(params[:id])).limit(10)
# models/photo.rb
scope :most_recent_starting_from, -> (photo) { order(created_at: :asc).where('created_at >= ?', photo.created_at) }
Example Usage
photo = Photo.find(123)
ten_next_created_photos_after_photo = Photo.most_recent_starting_from(photo).limit(10)
You could write a scope that just takes everything from the current Photo
scope :offset_from, -> (photo) { where('id >= ?', photo.id) }
Photo.offset_from(Photo.find(params[:id]))......

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"

Rails Arel equivalent of this complex sql query

Here is the original logic
(scrape_datas = ScrapeData.find(
:all, :conditions =>
"artist_status = 'NOT_FOUND'
AND blacklisted = 1
AND extracted = 0
and not EXISTS(
SELECT * FROM artist_name_suggestions where original = artist_name
)
I've been able to split up the first part better
scrape_datas = ScrapeData.where(
:artist_status => 'NOT_FOUND',
:blacklisted => 1,
:extracted => 0
)
Although having issues getting the "and not EXISTS" query into the mix
and not EXISTS(
SELECT * FROM artist_name_suggestions where original = artist_name
)
Thanks!
Firstly you can extract simple scopes:
scope :not_found, where(:artist_status => 'NOT_FOUND')
scope :blacklisted, where(:blacklisted => 1)
scope :extracted, where(:extracted => 0)
Then add a query method (assume artist_name is a column of scrape_datas):
def self.no_suggestions
scrape_datas = ScrapeData.arel_table
suggestions = ArtistNameSuggestion.arel_table
where(ArtistNameSuggestion.where(
suggestions[:original].eq(scrape_datas[:artist_name])
).exists.not)
end
Now you can do something like this:
ScrapeData.not_found.blacklisted.extracted.no_suggestions

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
]
)

Optimise ignoring of undefined variables when building find conditions in Rails

I have a an method that retrieves Groups that are present in certain areas. Groups are given a country_id, region_id and city_id
The UI gives three select boxes to choose a country, a region from that country and then a city from that region. To find all groups in a particular city, I have this code:
#groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
This all works fine, but I also want it to find all groups in an area when the lower criteria isn't specified. For example, If a country and region are given, but not city, I'd like to find it by the region.
What I'm doing is this:
if !params[:city_id].nil?
#groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
else
if !params[:region_id].nil?
#groups = Group.find(:all, :conditions => {:region_id => params[:region_id]})
else
#groups = Group.find(:all, :conditions => {:country_id => params[:country_id]})
end
end
This works perfectly well, but it seems like it's a little inefficient. Am I doing it the best way or can I streamline a little?
One idea I had was to have a single find checking against all parameters, but I could not work out how to effectively 'ignore' parameters that were nil - my main thought was to check which ones were not set and set them to something like '*' or 'true', but that's not how SQL plays the game.
Sounds like a job for named scopes:
class Group < ActiveRecord::Base
named_scope :in_city, lambda { |city_id| {
:conditions => { :city_id => city_id }
}}
named_scope :in_region, lambda { |region_id | {
:conditions => { :region_id => region_id }
}}
named_scope :in_country, lambda { |country_id | {
:conditions => { :country_id => country_id }
}}
end
This establishes some simple scopes for restricting the Group records. Presumably you have indexed your database properly so these are quick to resolve.
The controller is much easier to implement then:
def index
#group_scope = Group
if (!params[:city_id].blank?)
#group_scope = #group_scope.in_city(params[:city_id])
elsif (!params[:region_id].blank?)
#group_scope = #group_scope.in_region(params[:region_id])
elsif (!params[:country_id].blank?)
#group_scope = #group_scope.in_country(params[:country_id])
end
#groups = #group_scope.all
end
Generally you should be testing for .blank? instead of .nil? as some form elements can send in empty results, such as a select with something akin to "All" as the default.
You could use some Ruby idioms to get something a little more succinct.
Try something like this: (untested code!)
def index
#groups = Group.find :all, :conditions => [:city_id, :region_id, :country_id].inject {} do |conditions, name|
conditions[name] = params[name] unless params[name].blank?
conditions
end
end
If every value in params is a candidate for :conditions you can just do this:
#groups = Group.all(:conditions => params.reject { |idx, val| val.nil? })
This just throws out nil values from params and uses the remaining values for conditions.
If you don't want to use all of the values in params, you have two options. You can just get rid of a bunch of redundancy in your original code:
conditions = if !params[:city_id].nil?
{ :city_id => params[:city_id] }
elsif !params[:region_id].nil?
{ :region_id => params[:region_id] }
else
{ :country_id => params[:country_id] }
end
#groups = Group.all(:conditions => conditions)
You can knock of a few more lines like this, but it sacrifices a bit of readability IMO:
conditions = if !params[:city_id].nil? then { :city_id => params[:city_id] }
elsif !params[:region_id].nil? then { :region_id => params[:region_id] }
else { :country_id => params[:country_id] }
end
Or you can do something like this:
conditions = [:city_id, :region_id, :country_id].inject({}) do |hsh, sym|
hsh[sym] = params[sym] unless params[sym].nil?
hsh
end
#groups = Group.all(:conditions => conditions)
This has the advantage that you don't need to add another condition for each symbol.