Module: AutomaticRecord::AutoCreate::ClassMethods
- Defined in:
- lib/automatic_record/auto_create.rb
Instance Method Summary collapse
-
#auto_create(assoc, default_attrs_or_block = {}) ⇒ Object
Specifies that the given association should be created automaticaly whenever it is accessed, if it does not already exist.
Instance Method Details
#auto_create(assoc, default_attrs_or_block = {}) ⇒ Object
Specifies that the given association should be created automaticaly whenever it is accessed, if it does not already exist. This method should only be used on associations that are defined as either :belongs_to or :has_one.
Example
class User < ActiveRecord::Base
has_one :preference
auto_create :preference
end
Options
Pass a list of default attributes:
auto_create :preference, :language => 'en', :notifications => true
Pass a block to be used for object creation:
auto_create :preference, ->(user){ user.create_preference(:language => 'en', :notifications => true) }
30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/automatic_record/auto_create.rb', line 30 def auto_create(assoc, default_attrs_or_block={}) reflection = reflect_on_association(assoc) if reflection.nil? raise AutomaticRecord::Error::MissingAssociation.new(assoc) elsif !(reflection.has_one? || reflection.belongs_to?) raise AutomaticRecord::Error::InvalidAssociation.new(assoc) else define_method(assoc) do |force_reload=false| return get_or_auto_create_assoc(assoc, force_reload, default_attrs_or_block) end end end |