Skip to content

Instantly share code, notes, and snippets.

@Nimster
Created August 6, 2011 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nimster/1129101 to your computer and use it in GitHub Desktop.
Save Nimster/1129101 to your computer and use it in GitHub Desktop.
Rails lookup v3 - String accessors for the lookup type
def lookup(as_name)
#...
#Now, define the foreign key from Car to CarType.
belongs_to lookup_name.to_s.to_sym, :foreign_key => "#{as_name}".to_sym
validates "#{as_name.to_s}_id".to_sym, :presence => true
#Now we define the "delegates" that will allow us to just set call car.car_type = "Sports"
#Define a setter for car_type
define_method("#{as_name.to_s}_id=") do |id|
#We would have used instance_variable_get. However rails maintains a hash of attributes
#that we must use to play nicely along with rails. Here we write the ID of the value
#instead of the value itself inside the field.
write_attribute "#{as_name.to_s}".to_sym, id
end
# Setter via String
define_method("#{as_name.to_s}=") do |val|
id = cls.gen_id_for val
write_attribute "#{as_name.to_s}".to_sym, id
end
# Getter for the ID
define_method("#{as_name.to_s}_id") do
read_attribute "#{as_name.to_s}".to_sym
end
#Define the getter
define_method("#{as_name.to_s}") do
id = read_attribute "#{as_name.to_s}".to_sym
if not id.nil?
value = cls.name_for id
if value.nil?
# This is reached in case many processes use the DB and some other process
# inserted a new value that we were not aware of, but who's ID was inserted
# into this object.
lookup_obj = cls.find_by_id id
if not lookup_obj.nil?
cls.name_for id, lookup_obj.name
cls.id_for lookup_obj.name, id
end
end
end
value
end
#...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment