Reputation: 635
I am trying to create a search form with multiple columns(all from the same model) Now I want to set the value of all other columns as nil if the category column is set to a particular value. Something like this-
#app/models/question.rb
if (cateogry.matches => 'Exam Questions')
query = query.where("name like ? AND course like ? AND year like ?", "%#{query}%", "%#{query}%", "%#{query}%")
else
query = query.where("name like ?","%#{query}%")
end
The search form is a basic form using get method.
Upvotes: 0
Views: 625
Reputation: 1277
You could use scopes for that.
class Question < ActiveRecord::Base
...
# Scope for searching by exam
scope :by_exam, -> (name, course, year) {
match(:name, name).
match(:course).
match(:year, year)
}
# Scope forsearching by nma
scope :by_name, ->(name) { match(:name, name) }
# Helper scope for matching
scope :match, ->(key, value) { where(arel_table[key].matches("%#{value}%"} }
end
So in your controller
if (cateogry.matches => 'Exam Questions')
Question.by_exam(params[:name], params[:course], params[:year])
else
Question.by_name(params[:name])
end
Upvotes: 1