Jump to content

The ultimate community for Ruby on Rails developers.


Photo

adding searchablecolumns

search tables

  • Please log in to reply
2 replies to this topic

#1 DvDj

DvDj

    Signalman

  • Members
  • 20 posts
  • LocationUnited Kingdom

Posted 26 July 2014 - 04:39 PM

Hi all,

 

So I followed a brilliant 'RailsCasts' tutorial on adding pagination to my products table along with a search function, which is all working well.  However, the search function is restricted to one column of information and i am wondering if i can easily add more columns?

	def self.search(search)
		if search
			where('item_code LIKE ?', "%#{search}%")
		else
			scoped
		end
	end

So above is what is currently working well with searches being performed on the 'Item Code' column.  I tried adding a column with the following code. 

	def self.search(search)
		if search
			where('item_code LIKE ?', 'colour_description LIKE ?', "%#{search}%")
		else
			scoped
		end
	end

And also.

	def self.search(search)
		if search
			where('item_code, colour_description LIKE ?', "%#{search}%")
		else
			scoped
		end
	end

Neither of which work.  I thought that 'else scoped' would allow me to add to this search function.

 

Is this function restricted to one column?  I don't really want to be adding something like 'Sphinx' as i am on SQLlite which Sphinx is not compatible with.

 

Any advice is much appreciated.



#2 Ohm

Ohm

    Driver

  • Moderators
  • 449 posts
  • LocationCopenhagen

Posted 26 July 2014 - 09:20 PM   Best Answer

You need to write the correct SQL for searching either in item_code or colour_description, using SQLs OR.

 

This can be done like so:

def self.search(search)
  if search
    where('item_code ILIKE :search OR colour_description LIKE :search', search: "%#{search}%")
  else
    scoped
  end
end

  • Jamie and DvDj like this

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk


#3 DvDj

DvDj

    Signalman

  • Members
  • 20 posts
  • LocationUnited Kingdom

Posted 26 July 2014 - 09:54 PM

Guard,

 

Thank you for taking the time to help me with this, it works perfectly and has really helped.

 

Stuart







Also tagged with one or more of these keywords: search, tables

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users