简体   繁体   中英

Ruby on Rails ActiveRecord How to get a where clause to always evaluate to be true

I am making a simple resource app. The app has filters in three major categories (courses, years, resource type) that may or may not be present. These filters are passed through parameters in an URL. I store these parameters in an 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 (ex. maybe resourceType is empty so I want a particular resource from a particular year but it can be of any type), it returns a empty set. Is there a way to use a wild card in this function? If not can someone propose a suitable solution?

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)

You could 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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM