Skip to content

Commit

Permalink
Cherry-pick assoc names for model
Browse files Browse the repository at this point in the history
  • Loading branch information
solnic committed Dec 6, 2023
1 parent 8756826 commit c2c244a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
21 changes: 12 additions & 9 deletions lib/rom/factory/tuple_evaluator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def initialize(attributes, relation, traits = {})
@sequence = Sequences[relation]
end

def model(traits)
@relation.combine(*assoc_names(traits)).mapper.model
def model(traits, combine: assoc_names(traits))
@relation.combine(*combine).mapper.model
end

# @api private
Expand All @@ -51,22 +51,25 @@ def struct(*traits, **attrs)

attributes.merge!(materialized_callables)

associations = assoc_names(traits)
.reject { |name| attrs.key?(name) && attrs[name].nil? }
associations = attrs.slice(*assoc_names(traits)).merge(assoc_names(traits)
.select { |key|
build_assoc?(key, attributes)
}
.map { |key|
if (assoc = @attributes[key]) && assoc.count.positive?
[key, build_assoc_attrs(key, attributes[relation.primary_key], attributes[key])]
end
[key, build_assoc_attrs(key, attributes[relation.primary_key], attributes[key])]
}
.compact
.to_h
.to_h)

attributes = relation.output_schema[attributes]
attributes.update(associations)

model(traits).new(attributes)
end

def build_assoc?(key, attributes)
attributes.key?(key) && attributes[key] != [] && !attributes[key].nil?
end

def build_assoc_attrs(key, fk, value)
if value.is_a?(Array)
value.map { |el| build_assoc_attrs(key, fk, el) }
Expand Down
19 changes: 17 additions & 2 deletions spec/integration/rom/factory_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@
end

factories.define(:user) do |f|
f.first_name "Jane"
f.last_name "Doe"
f.email "[email protected]"
f.timestamps
f.association(:tasks, count: 2)
end
Expand All @@ -69,6 +72,18 @@
expect(user_with_tasks.tasks).to all(have_attributes(user_id: user_with_tasks.id))
end

it "sets a value explicitly" do
user = factories.structs[:user, tasks: []]

expect(user.tasks).to be_empty
end

it "sets a value explicitly when persisting" do
user = factories[:user, tasks: []]

expect(user.tasks).to be_empty
end

it "does not create records when building child" do
factories.structs[:task]

Expand Down Expand Up @@ -111,13 +126,13 @@
it "does not build associated struct if it's set to nil explicitly" do
task = factories.structs[:task, user: nil]

expect(task.user).to be_nil
expect(task.user).to be(nil)
end

it "does not persist associated struct if it's set to nil explicitly" do
task = factories[:task, user: nil]

expect(task.user).to be_nil
expect(task.user).to be(nil)
end

it "creates the associated record with provided attributes" do
Expand Down

0 comments on commit c2c244a

Please sign in to comment.