hyper-mesh icon indicating copy to clipboard operation
hyper-mesh copied to clipboard

add `#build / #new` and make `<< / #push` save like active record does

Open catmando opened this issue 7 years ago • 2 comments

<< should save, and build should not.

change push's name to build (be careful push / << may be used internally in Hypermesh) and add a new push which does build(...).save and returns self.

only allow build on root collections (not scopes) as the scope behavior is to fill in the attributes to match the scope. (see https://github.com/ruby-hyperloop/hyper-mesh/issues/64)

have to add the old behavior back into the deprecation gem.

catmando avatar Feb 09 '18 22:02 catmando

Patch for build - just extending current << behaviour to instantiate the model:

module ReactiveRecord
  class Collection
    unless method_defined?(:build)
      def build(**attrs)
        self << @association.klass.new(**attrs)
      end
    end
  end
end

Sketch of other methods, but I'm not sure the behaviour matches Rails, the docs aren't clear enough so some experimentation and looking at Rails code needed.

def <<(other)
  # push is current alias of <<
  push(other).save
end

def create(**attrs)
  build(**attrs)
  @owner.save
end

def create!(**attrs)
  build(**attrs)
  @owner.save!
end

sfcgeorge avatar Feb 09 '18 22:02 sfcgeorge

push and << are aliases so it would have to be

def <<(other)
  build(other).tap { |r| r.save }
end

catmando avatar Feb 09 '18 23:02 catmando