-
-
Save jamescook/943125 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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