Daisy chaining conditions in Rails controller action. - ruby-on-rails

The index method of my controller looks as follows:
def index
if params["feed_source_id"]
#feeds = Feed.find_all_by_feed_source_id(params["feed_source_id"])
else
#feeds = Feed.all
end
I just added the Metasearch Gem to my app, and it defines the search in my index as:
#search = Feed.search(params[:search])
How can I daisy chain both of these conditions so that #search will perform the search as well as include the find_all_by_feed_source_id condition?

Not sure what you're aiming at - besides doing both searches in the index action? Do you want a union or intersection of both search results?
If you want a union, you could do something like
#feeds = #feeds | #search.all
in addition to all the code above, which would give you a terrible performance.
I had a brief look at the Metasearch Gem, and it should give you the possibility to include the feed_source_id as one of the parameters.

You want the AND of these conditions, right?
I think this should work:
Feed.search({ :feed_source_id_eq => params[:feed_source_id] }.merge(params[:search]))

Related

How to make search box case-insensitive in rails?

I have simple search form in Rails, but when I using the search box, I need to enter the name exactly.
For instance, when I try to search for "more" it doesn't return anything, but when I do with "More", then it returns the records, So it seems like it behaves in a case-sensitive way.
Is it possible to make this case-sensitive way?
Here is my code
def self.search(search)
if search
star = Star.find_by(who: search)
if star
self.where(star_id: star)
else
Post.all
end
else
Post.all
end
end
You could do something like:
star = Star.where("UPPER(who) = ?", search.upcase).take
or
star = Star.where("LOWER(who) = ?", search.downcase).take
Either way, this coerces both your search term as well as the who value in the database before comparing them, which should get you the results that you need

Exact Term Search In Rails

I'm trying to build a basic search where only the entire exact search term shows results. Currently it is showing results based on individual words.
Here's the code from the model:
def search
find(:all, :conditions => ['term' == "%#{search}%"])
end
Sorry in advance. I'm very new to rails!
Thank you.
Remove the % from "%#{search}%" so it's "#{search}".
% is a wildcard that matches every result containing the word. So "%tea%" for example would match tear, nestea, and steam, when that's not what you want.
This should yield an exact match:
def search
find(:all, :conditions => ['term' == "#{search}"])
end
Your code doesn't work for several reasons.
You do not pass any value to that method. Therefore search will always be nil.
The ['term' == "%#{search}%"] condition doesn't make much sense because - as I said before - search is undefined and therefore the condition will is the same as ['term' == "%%"]. The string term is not equal to %% therefore the whole condition is basically: [false].
Rails 5.0 uses a different syntax for queries. The syntax you used is very old and doesn't work anymore.
I would do something like this:
# in your model
scope :search, -> (q) {
q.present? ? where("column_name LIKE :query", query: "%#{q}%") :none
}
# in your controller
def set_index
#b = Best.search(params[:search]).order(:cached_weighted_score => :desc)
end

How to filter results by their associations when using PG search gem?

I am using PG search gem in my Rails app. Say I get a set of articles in my controller:
#articles = Article.search(params[:search]).with_pg_search_highlight
the problem with PG search here is that I get back an array, instead of AR object. So now I cannot do something like
#research_articles = #articles.where(category: 'research')
Because I will get a
undefined method `where' for Array
Now I can make several queries from that one action, but what would be a better solution to this problem?
pg_search gem provides pg_search_scope.
See the doc https://github.com/Casecommons/pg_search#pg_search_scope
You can also chain where condition with pg_search_scope.
What about changing the chain?
#articles = Article.where(category: 'research').search(params[:search]).with_pg_search_highlight
EDIT:
A way without making 2 queries would be:
#found_articles = Article.search(params[:search]).with_pg_search_highlight
#research_articles = #found_articles.select { |article| article.category == "research" }
You probably should define a scope (or even simple getter would be enough here) and reuse it:
def simple_search
pure = Article.search(params[:search])
(block_given? ? yield(pure) : pure).with_pg_search_highlight
end
And then:
#articles = simple_search
#research_articles = simple_search { |ss| ss.where(category: 'research') }

How do I do an "or" based search in sunspot?

I have several categories of facets I'm looking for and in one I want, when the user clicks more than one filter in that particular category, to have the results sunspot returns include everything that matches either of the choices, not only both. I tried this:
#search = ProfileSearch.new(search_params) do
facet_restriction = with(:grad_year,params[:grad_year])
facet(:grad_year, :exclude => facet_restriction)
end
But that doesn't seem to be working at all? Am I not using multiselect facets in the appropriate way or should I be looking at doing something entirely different?
Any thoughts would be appreciated.
I think it should be
#search = ProfileSearch.search(search_params) do
facet_restriction = with(:grad_year,params[:grad_year])
facet(:grad_year, :exclude => facet_restriction)
end
I do something like this:
grad_year_exclusions = []
if params[:grad_year].present?
grad_year_exclusions << with(:grad_year).any_of(params[:grad_year])
end
grad_year_exclusions.compact!
grad_year_exclusions = nil if grad_year_exclusions.empty?
facet(:grad_year, exclude: grad_year_exclusions)
(params[:grad_year] being an array)
Hope this helps.

rails "where" statement: How do i ignore blank params

I am pretty new to Rails and I have a feeling I'm approaching this from the wrong angle but here it goes... I have a list page that displays vehicles and i am trying to add filter functionality where the user can filter the results by vehicle_size, manufacturer and/or payment_options.
Using three select form fields the user can set the values of :vehicle_size, :manufacturer and/or :payment_options parameters and submit these values to the controller where i'm using a
#vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, :vehicle_size => params[:vehicle_size] )
kind of query. this works fine for individual params (the above returns results for the correct vehicle size) but I want to be able to pass in all 3 params without getting no results if one of the parameters is left blank..
Is there a way of doing this without going through the process of writing if statements that define different where statements depending on what params are set? This could become very tedious if I add more filter options.. perhaps some sort of inline if has_key solution to the effect of:
#vehicles = Vehicle.order("vehicles.id ASC").where(:visible => true, if(params.has_key?(:vehicle_size):vehicle_size => params[:vehicle_size], end if(params.has_key?(:manufacturer):manufacturer => params[:manufacturer] end )
You can do:
#vehicles = Vehicle.order('vehicles.id ASC')
if params[:vehicle_size].present?
#vehicles = #vehicles.where(vehicle_size: params[:vehicle_size])
end
Or, you can create scope in your model:
scope :vehicle_size, ->(vehicle_size) { where(vehicle_size: vehicle_size) if vehicle_size.present? }
Or, according to this answer, you can create class method:
def self.vehicle_size(vehicle_size)
if vehicle_size.present?
where(vehicle_size: vehicle_size)
else
scoped # `all` if you use Rails 4
end
end
You call both scope and class method in your controller with, for example:
#vehicles = Vehicle.order('vehicles.id ASC').vehicle_size(params[:vehicle_size])
You can do same thing with remaining parameters respectively.
The has_scope gem applies scope methods to your search queries, and by default it ignores when parameters are empty, it might be worth checking

Resources