7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/ar_lookups/activerecord_ext.rb', line 7
def lookup(column, *args)
options = args.
lookup_model = args.first
options.reverse_merge!(key_column: :key, name_column: :name)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{column}; super; end
def #{column}=(value); super; end
RUBY
ar_lookups[column] = lookup_model || implicit_lookup_class(column)
mod = Module.new
include mod
mod.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{column}
keys = read_attribute(:#{column})
klass = self.class.ar_lookups[:#{column}]
return klass.none if keys.blank?
self.class.ar_lookups[:#{column}].where('#{options[:key_column]} IN (?)', keys)#.pluck(:#{options[:key_column]}, :#{options[:name_column]})]
end
def #{column}_ids
read_attribute(:#{column})
end
def #{column}=(val)
write_attribute(:#{column}, val)
end
RUBY
end
|