class DatastaxRails::Associations::SingularAssociation

Encapsulates the common functionality between belongs_to and has_one relationships

Public Instance Methods

build(attributes = {}, options = {}) { |record| ... } click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 24
def build(attributes = {}, options = {})
  record = build_record(attributes, options)
  yield(record) if block_given?
  set_new_record(record)
  record
end
create(attributes = {}, options = {}, &block) click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 16
def create(attributes = {}, options = {}, &block)
  create_record(attributes, options, &block)
end
create!(attributes = {}, options = {}, &block) click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 20
def create!(attributes = {}, options = {}, &block)
  create_record(attributes, options, true, &block)
end
reader(force_reload = false) click to toggle source

Implements the reader method, e.g. foo.bar for Foo.has_one :bar

# File lib/datastax_rails/associations/singular_association.rb, line 6
def reader(force_reload = false)
  reload if force_reload || !loaded? || stale_target?
  target
end
writer(record) click to toggle source

Implements the writer method, e.g. foo.items= for Foo.has_many :items

# File lib/datastax_rails/associations/singular_association.rb, line 12
def writer(record)
  replace(record)
end

Private Instance Methods

create_record(attributes, options, raise_error = false) { |record| ... } click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 50
def create_record(attributes, options, raise_error = false)
  record = build_record(attributes, options)
  yield(record) if block_given?
  saved = record.save
  set_new_record(record)
  fail RecordInvalid.new(record) if !saved && raise_error
  record
end
create_scope() click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 33
def create_scope
  scoped.scope_for_create.stringify_keys.except('id')
end
find_target() click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 37
def find_target
  scoped.first.tap { |record| set_inverse_instance(record) }
end
replace(_record) click to toggle source

Implemented by subclasses

# File lib/datastax_rails/associations/singular_association.rb, line 42
def replace(_record)
  fail NotImplementedError, 'Subclasses must implement a replace(record) method'
end
set_new_record(record) click to toggle source
# File lib/datastax_rails/associations/singular_association.rb, line 46
def set_new_record(record) # rubocop:disable Style/AccessorMethodName
  replace(record)
end