I would like some help to clean up this action, especially from @companies
and downward. The comments should be enough to explain :)
def search
@query = params[:query]
unless @query.blank?
@query.strip!
#Get tags with fuzzy match
tags = Tag.where("name LIKE ?", "%#{@query}%").pluck(:name)
#Get vouchers with these tags
@vouchers = Voucher.tagged_with(tags, :any => true)
#Get companies with these tags, and add their vouchers to the list
@companies = Company.tagged_with(tags, :any => true)
@companies.each do |company|
#Because can't merge with nil. Can this be re-written?
if @vouchers.empty?
@vouchers = company.vouchers
else
@vouchers.merge(company.vouchers)
end
end
#Get every voucher's category. Can this be re-written?
@categories = []
@vouchers.each do |voucher|
@categories << voucher.categories
end
#Because can't call .flatten on nil
if @categories.any?
#Need to flatten because the array will contain an arrays of categories [[],[],[]]
@categories.flatten!.uniq # I don't really want .flatten.uniq in the view, or?
end
end
end