Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

SQLListColumn

DZone's Guide to

SQLListColumn

·
Free Resource
a string/text column with comma-separated values


class SQLListColumn < String
  SEPARATOR = ','
  def contains(value)
    "#{self} like '%#{SEPARATOR}#{value}#{SEPARATOR}%' or #{self} like '#{value}#{SEPARATOR}%' or #{self} like '%#{SEPARATOR}#{value}' or #{self} = '#{value}'"
  end
end


Usage:


SQLListColumn.new('admins').contains('tmorgan')


...gives you a string you can use in a SQL query:


"admins like '%,tmorgan,%' or admins like 'tmorgan,%' or admins like '%,tmorgan' or admins = 'tmorgan'"


Rails usage might look like this:


Program.find(
  :all,
  :conditions => \
    SQLListColumn.new('admins').contains(username) \
    + ' or ' + \
    SQLListColumn.new('viewers').contains(username),
  :order => 'name'
)
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}