Ruby on Rails ActiveRecord How to get a where clause that will always be considered true
Hi guys so i am very new to rubies on rails and i am making a simple resource app. The application has filters for three main categories (courses, years, resource type), which may or may not be present. These filters are passed through parameters in the URL. I store these parameters in 3 arrays called courses, years, resource type. However, sometimes the array may be empty. When I try to run a search with an empty array (for example, resourceType is empty, so I want a specific resource from a specific year, but it can be of any type), it returns an empty set. Is there a way to use wildcard in this function? If not, can someone suggest a suitable solution? Any help would be really appreciated
Here is the function I am trying to run.
@resources= Resource.where(class_name: courses,
year: years,
resource_type: resourceTypes)
.paginate(page: params[:page], per_page: 10)
.order(:cached_votes_total => :desc)
source to share
Try:
query = { }
query[:class_name] = courses if courses.present?
query[:year] = years if years.present?
query[:resource_type] = coursresourceTypeses if coursresourceTypeses.present?
@resources = Resource.where(query).paginate(page: params[:page], per_page: 10).order(cached_votes_total: :desc)
source to share
You can always do something like:
@resources = Resource.all
@resources = @resources.where(class_name: courses) if courses.any?
@resources = @resources.where(resource_type: resourceTypes) if resourceTypes.any?
@resources = @resources.where(year: years) if years.any?
@resources = @resources.paginate(page: params[:page], per_page: 10).order(:cached_votes_total => :desc)
source to share