Skip to content

Instantly share code, notes, and snippets.

@jamescook
Forked from benolee/gist:943073
Created April 26, 2011 20:57
Show Gist options
  • Save jamescook/943125 to your computer and use it in GitHub Desktop.
Save jamescook/943125 to your computer and use it in GitHub Desktop.
# This is the current solution. It merely validates the string's inclusion in
# the given list, and saves it as a string.
ActiveRecord::Schema.define(:version => 20110101000000) do
create_table "foos", :force => true do |t|
t.string "bar"
end
end
class Foo < ActiveRecord::Base
validates_inclusion_of :bar, :in => ["a", "b", "c"]
end
# It might be helpful to add a list of the available values for the bar attribute
class Foo < ActiveRecord::Base
validates_inclusion_of :bar, :in => self.class.bars
class << self
def bars
["a","b","c"]
end
end
end
# Or I could reuse a solution I saw on the client model in xrono, storing the
# value as an integer in the db, and defining custom getters and setters
ActiveRecord::Schema.define(:version => 20110101000000) do
create_table "foos", :force => true do |t|
t.integer "bar"
end
end
class Foo < ActiveRecord::Base
validates_inclusion_of :bar, :in => self.class.bars.keys
def bar
self.class.bars[attributes[:bar]]
end
def bar=(value)
write_attribute(:bar, self.class.bars[value])
end
class << self
def bars
{
"a" => 1,
"b" => 2,
"c" => 3
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment