I searched the docs for how to implement relationships among entities (eg, one-to-many, many-to-many, etc), but didn't find any examples.
So I tried a reasonable guess. Here's my attempt at implementing a Person
who can be tagged with Tag
s:
require 'moocho_query'
require 'hanami/model'
require 'hanami/model/adapters/file_system_adapter'
class Person
include Hanami::Entity
attributes :name, :age, :tags
end
class Tag
include Hanami::Entity
attributes :name
end
class PersonRepository
include Hanami::Repository
end
class TagRepository
include Hanami::Repository
end
Hanami::Model.configure do
adapter type: :file_system, uri: './file_db'
mapping do
collection :people do
entity Person
repository PersonRepository
attribute :id, Integer
attribute :name, String
attribute :age, Integer
attribute :tags, type: Array[Tag]
end
collection :tags do
entity Tag
repository TagRepository
attribute :id, Integer
attribute :name, String
end
end
end.load!
me = Person.new(name: 'Jonah', age: 99)
t1 = Tag.new(name: 'programmer')
t2 = Tag.new(name: 'nice')
me.tags = [t1, t2]
PersonRepository.create(me)
This fails on the load!
call, with the following error:
/Users/x/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/hanami-utils-0.7.0/lib/hanami/utils/class.rb:90:in `load_from_pattern!': uninitialized constant (Hanami::Model::Mapping::Coercers::{:type=>[Tag]}|
{:type=>[Tag]}) (NameError)
from /Users/jg/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/hanami-model-0.6.0/lib/hanami/model/mapping/attribute.rb:80:in `coercer'
from /Users/jg/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/hanami-model-0.6.0/lib/hanami/model/mapping/attribute.rb:53:in `load_coercer'
What is the correct way to implement relationships in Hanami?
I know it's an old question, but I'll leave this answer in case somebody stumbles here:
Hanami added many-to-many support on version 1.1 http://hanamirb.org/guides/1.1/associations/has-many-through/
Basic setup
Migrations
Users table:
Stories table:
Comments table:
Repositories
User repository:
Story repository:
Comment repository:
Usage