aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/builder/singular_association.rb
blob: 638a2ec72a6e9957f26b9dfa464d3678aeaa576a (plain) (blame)
1
2
3
4
5
6
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
41
42
43
44
45
module ActiveRecord::Associations::Builder
  class SingularAssociation < Association #:nodoc:
    self.valid_options += [:remote, :dependent, :counter_cache, :primary_key, :inverse_of]

    def constructable?
      true
    end

    def define_accessors
      super
      define_constructors if constructable?
    end

    private

      def define_readers
        super
        name = self.name

        model.redefine_method("#{name}_loaded?") do
          ActiveSupport::Deprecation.warn(
            "Calling obj.#{name}_loaded? is deprecated. Please use " \
            "obj.association(:#{name}).loaded? instead."
          )
          association(name).loaded?
        end
      end

      def define_constructors
        name = self.name

        model.redefine_method("build_#{name}") do |*params, &block|
          association(name).build(*params, &block)
        end

        model.redefine_method("create_#{name}") do |*params, &block|
          association(name).create(*params, &block)
        end

        model.redefine_method("create_#{name}!") do |*params, &block|
          association(name).create!(*params, &block)
        end
      end
  end
end