Module: Volt::Associations::ClassMethods
- Defined in:
- lib/volt/models/associations.rb
Instance Method Summary collapse
- #belongs_to(method_name, key_name = nil) ⇒ Object
- #has_many(method_name, remote_key_name = nil) ⇒ Object
Instance Method Details
#belongs_to(method_name, key_name = nil) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/volt/models/associations.rb', line 4 def belongs_to(method_name, key_name=nil) # getter define_method(method_name) do association_with_root_model('belongs_to') do |root| # Lookup the associated model id lookup_key = send(:"_#{key_name || method_name}_id") # Return a promise for the belongs_to root.send(:"_#{method_name.pluralize}").where(:_id => lookup_key).fetch_first end end end |
#has_many(method_name, remote_key_name = nil) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/volt/models/associations.rb', line 17 def has_many(method_name, remote_key_name=nil) define_method(method_name) do association_with_root_model('has_many') do |root| id = self._id # The key will be "{this class name}_id" remote_key_name ||= :"#{path[-2].singularize}_id" root.send(:"_#{method_name.pluralize}!").where(remote_key_name => id) end end end |