Module: ActiveRecord::Associations::HasOneDefault

Extended by:
HasOneDefault
Included in:
HasOneDefault
Defined in:
lib/adva/active_record/has_one_default.rb

Instance Method Summary collapse

Instance Method Details

#has_one(association_id, options = {}) ⇒ Object


20
21
22
23
24
# File 'lib/adva/active_record/has_one_default.rb', line 20

def has_one(association_id, options = {})
  default = options.delete(:default)
  super
  has_one_default(association_id, default) if default
end

#has_one_default(association_id, default) ⇒ Object


26
27
28
29
30
31
32
33
34
# File 'lib/adva/active_record/has_one_default.rb', line 26

def has_one_default(association_id, default)
  default_scope includes(association_id) rescue nil # would raise during migrations. how to remove the rescue clause?
  validates_presence_of association_id

  define_method(:"#{association_id}_with_default") do
    send(:"#{association_id}_without_default") || send(:"#{association_id}=", send(default))
  end
  alias_method_chain association_id, :default
end