rom-rb / rom-rb.org

The official rom-rb website
https://rom-rb.org/
45 stars 108 forks source link

Error when running "Repositories » Writing Aggregates" sample #302

Closed mike-shock closed 5 years ago

mike-shock commented 5 years ago

I'm trying to run the sample from the page: https://rom-rb.org/5.0/learn/repositories/writing-aggregates/

But the line

users.combine(:tasks).command(:create).call(user)

causes the error:

Traceback (most recent call last):
    8: from w1.rb:44:in `<main>'
    7: from w1.rb:38:in `create_with_tasks'
    6: from /home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-repository-1.4.0/lib/rom/repository/relation_proxy/combine.rb:59:in `combine'
    5: from /home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-repository-1.4.0/lib/rom/repository/relation_proxy/combine.rb:59:in `each'
    4: from /home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-repository-1.4.0/lib/rom/repository/relation_proxy/combine.rb:86:in `block in combine'
    3: from /home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-repository-1.4.0/lib/rom/repository/relation_proxy/combine.rb:255:in `combine_opts_for_assoc'
    2: from /home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-3.3.3/lib/rom/registry.rb:32:in `fetch'
    1: from /home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-3.3.3/lib/rom/registry.rb:32:in `fetch'
/home/t4503/.rvm/gems/ruby-2.6.5/gems/rom-3.3.3/lib/rom/registry.rb:35:in `block in fetch': **:tasks doesn't exist in ROM::RelationRegistry registry (ROM::Registry::ElementNotFoundError)**
solnic commented 5 years ago

You must have a typo somewhere because the example works, I copied/pasted it from the docs and it worked:

require 'rom-repository'

rom = ROM.container(:sql, 'sqlite::memory') do |config|
  config.default.create_table(:users) do
    primary_key :id
    column :name, String, null: false
    column :email, String, null: false
  end

  config.default.create_table(:tasks) do
    primary_key :id
    foreign_key :user_id, :users
    column :title, String, null: false
  end

  config.relation(:users) do
    schema(infer: true) do
      associations do
        has_many :tasks
      end
    end
  end

  config.relation(:tasks) do
    schema(infer: true) do
      associations do
        belongs_to :user
      end
    end
  end
end

class UserRepo < ROM::Repository[:users]
  def create_with_tasks(user)
    users.combine(:tasks).command(:create).call(user)
  end
end

user_repo = UserRepo.new(rom)

user = user_repo.create_with_tasks(
  name: 'Jane',
  email: 'jane@doe.org',
  tasks: [{ title: 'Task 1' }, { title: 'Task 2' }]
)

user.inspect
# #<ROM::Struct::User id=1 name="Jane" email="jane@doe.org" tasks=[#<ROM::Struct::Task id=1 user_id=1 title="Task 1">, #<ROM::Struct::Task id=2 user_id=1 title="Task 2">]>