Introducing many-to-many relationships (and others) with the Hanami

I was looking for documents for how to implement relationships between objects (for example, one-to-many, many-to-many, etc.), but I did not find any examples.

So I tried a reasonable guess. Here is my attempt to implement Person , which may be tagged 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 when calling load! 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 right way to implement a relationship in Hanami?

+5
source share
2 answers

Starting with version 0.7.0, it is impossible to implement relationships between objects. This is why the documentation does not have practical recommendations.

Out of curiosity, I asked this using a tweet that can be mistaken for an official word about entity relationships.

Like working in Hanami, objects are simply objects that you save in the database, which means that the data about the preservation of the object may differ from its layout.

I would like to suggest a tags method for a Person object. Inside this method you can get human tags. Something like that:

 def self.tags TagRepository.query do where(id: [tag-id-1, tag-id-2, ... , tag-id-n]) end.all end 

Although you will need to save the tag identifiers associated with the person to the database as an attribute of the person or using the connection table.

Know that this implementation will have a problem with n+1 query.

+3
source

from Hanami 0.9.0, there is initial support for associations. The first is one-to-many. Please check it out and see if this makes sense to you. Thanks

0
source

Source: https://habr.com/ru/post/1241893/


All Articles