Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created October 16, 2015 14:46
Show Gist options
  • Save jodosha/431091eebb41606b358a to your computer and use it in GitHub Desktop.
Save jodosha/431091eebb41606b358a to your computer and use it in GitHub Desktop.
Test for Lotus::Model associations
require 'bundler/setup'
require 'lotus/model'
require 'lotus/model/migrator'
require 'pg'
class Bicycle
include Lotus::Entity
attributes :parts
end
class BicycleRepository
include Lotus::Repository
end
class Part
include Lotus::Entity
attributes :bicycle_id, :name
end
class PartRepository
include Lotus::Repository
end
Lotus::Model.configure do
adapter type: :sql, uri: 'postgres://localhost/associations_test'
mapping do
collection :bicycles do
entity Bicycle
repository BicycleRepository
attribute :id, Integer
association :parts, [Part], collection: :parts, foreign_key: :user_id
end
collection :parts do
entity Part
repository PartRepository
attribute :id, Integer
attribute :bicycle_id, Integer
attribute :name, String
end
end
end.load!
Lotus::Model::Migrator.prepare
Lotus::Model.migration do
change do
create_table :bicycles do
primary_key :id
end
create_table :parts do
primary_key :id
foreign_key :bicycle_id, :bicycles, on_delete: :cascade, null: false
column :name, String
end
end
end.apply(::Sequel::DATABASES.first, :up)
b = Bicycle.new
b.parts << Part.new(name: 'wheel')
b = BicycleRepository.create(b)
puts b.inspect
@jodosha
Copy link
Author

jodosha commented Oct 16, 2015

First attempt

bundle exec ruby association_test.rb
association_test.rb:65:in `<main>': undefined method `<<' for nil:NilClass (NoMethodError)

Second attempt

Then I patched Bicycle like this:

class Bicycle
  include Lotus::Entity
  attributes :parts

  def parts
    @parts || []
  end
end
bundle exec ruby association_test.rb
#<Bicycle:0x007f84aa161e40 @id=1 @parts=[]>
[]

@hlegius
Copy link

hlegius commented Oct 16, 2015

What's the intention here? Is to save all Part when save Bicycle with BicycleRepository.create(bicycle)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment