Skip to content

Instantly share code, notes, and snippets.

@benolee
Created April 26, 2011 20:37
Show Gist options
  • Select an option

  • Save benolee/943073 to your computer and use it in GitHub Desktop.

Select an option

Save benolee/943073 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.values
def bar
self.class.bars[attributes[:bar]]
end
def bar=(value)
write_attribute(:bar, self.class.bars.invert[value])
end
class << self
def bars
{
1 => "a",
2 => "b",
3 => "c"
}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment