module ActiveModel::Associations::ClassMethods

Public Instance Methods

belongs_to(name, scope = nil, options = {}) click to toggle source

define association like ActiveRecord

# File lib/active_model/associations.rb, line 24
def belongs_to(name, scope = nil, options = {})
  reflection = ActiveRecord::Associations::Builder::BelongsTo.build(self, name, scope, options)
  ActiveRecord::Reflection.add_reflection self, name, reflection
end
has_many(name, scope = nil, options = {}, &extension) click to toggle source

define association like ActiveRecord

# File lib/active_model/associations.rb, line 30
      def has_many(name, scope = nil, options = {}, &extension)
        options.reverse_merge!(active_model: true, target_ids: "#{name.to_s.singularize}_ids")
        if scope.is_a?(Hash)
          options.merge!(scope)
          scope = nil
        end

        reflection = ActiveRecord::Associations::Builder::HasManyForActiveModel.build(self, name, scope, options, &extension)
        ActiveRecord::Reflection.add_reflection self, name, reflection

        mixin = generated_association_methods
        mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
          def #{options[:target_ids]}=(other_ids)
            @#{options[:target_ids]} = other_ids
            association(:#{name}).reset
            association(:#{name}).reset_scope
            @#{options[:target_ids]}
          end
        CODE
      end