Over a million developers have joined DZone.

SQLListColumn

·
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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}