relation 0.5.2 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README2.md ADDED
@@ -0,0 +1,219 @@
1
+ # Relation
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/relation?color=168AFE&logo=rubygems&logoColor=FE1616)](https://rubygems.org/gems/relation)
4
+ [![Downloads](https://img.shields.io/gem/dt/relation?color=168AFE&logo=rubygems&logoColor=FE1616)](https://rubygems.org/gems/relation)
5
+ [![GitHub Build](https://img.shields.io/github/actions/workflow/status/matique/relation/rake.yml?logo=github)](https://github.com/matique/relation/actions/workflows/rake.yml)
6
+ [![Ruby Style Guide](https://img.shields.io/badge/code_style-standard-168AFE.svg)](https://github.com/standardrb/standard)
7
+ [![MIT License](https://img.shields.io/badge/license-MIT-168AFE.svg)](http://choosealicense.com/licenses/mit/)
8
+
9
+ **Relation** provides a generic way to establish relationships
10
+ between arbitrary ActiveRecord records without modifying
11
+ their respective database tables.
12
+
13
+ All relationships are stored in a single additional database table.
14
+
15
+ ~~~ruby
16
+ Relation.add order, user
17
+ Relation.add order, product
18
+ Relation.add order, another_user
19
+
20
+ Relation.references order, User # => [user, another_user]
21
+ Relation.references order, Product # => [product]
22
+
23
+ Relation.followers user, Order # => [order]
24
+ ~~~
25
+
26
+ Relationships can connect records of different models,
27
+ including records belonging to the same model.
28
+
29
+ ## Installation
30
+
31
+ Add the gem to your Gemfile:
32
+
33
+ ~~~ruby
34
+ gem "relation"
35
+ ~~~
36
+
37
+ Install it:
38
+
39
+ ~~~ruby
40
+ bundle install
41
+ ~~~
42
+
43
+ Create the `relations` table using the migration provided by the gem
44
+ or create it manually:
45
+
46
+ ~~~ruby
47
+ class CreateRelations < ActiveRecord::Migration[8.0]
48
+ def change
49
+ create_table :relations, id: false do |t|
50
+ t.string :from_name, null: false
51
+ t.bigint :from_id, null: false
52
+ t.string :to_name, null: false
53
+ t.bigint :to_id, null: false
54
+
55
+ t.index [:from_name, :from_id, :to_name, :to_id], unique: true
56
+ t.index [:to_name, :to_id, :from_name, :from_id]
57
+ end
58
+ end
59
+ end
60
+ ~~~
61
+
62
+ Run the migration:
63
+
64
+ ~~~ruby
65
+ bin/rails db:migrate
66
+ ~~~
67
+
68
+ Use the migration version matching your Rails version.
69
+
70
+ ## Usage
71
+
72
+ Assume the following ActiveRecord models:
73
+
74
+ ~~~ruby
75
+ class Order < ApplicationRecord; end
76
+ class User < ApplicationRecord; end
77
+ class Product < ApplicationRecord; end
78
+ ~~~
79
+
80
+ All records must be persisted before using the object API.
81
+
82
+ ### Creating relationships
83
+
84
+ Use `Relation.add` to establish a directed relationship:
85
+
86
+ ~~~ruby
87
+ Relation.add order, user
88
+ Relation.add order, user2
89
+ Relation.add order, product
90
+ ~~~
91
+
92
+ The first argument is the source record and the second is the target record.
93
+ Adding the same relationship multiple times does not create duplicates.
94
+
95
+ ### Finding related records
96
+
97
+ Use `Relation.references` to retrieve records referenced by
98
+ a particular record.
99
+
100
+ ~~~ruby
101
+ Relation.references order, User # => [user, user2]
102
+ Relation.references order, Product # => [product]
103
+ ~~~
104
+
105
+ Use `Relation.followers` to retrieve records that reference
106
+ a particular record:
107
+
108
+ ~~~ruby
109
+ Relation.followers user, Order # => [order]
110
+ ~~~
111
+
112
+ Both methods return ActiveRecord relations,
113
+ allowing additional query conditions:
114
+
115
+ ~~~ruby
116
+ Relation.references(order, User).where(active: true)
117
+ Relation.followers(user, Order).where(status: :active)
118
+ ~~~
119
+
120
+ ### Removing relationships
121
+
122
+ Use `Relation.remove` to remove a relationship:
123
+
124
+ ~~~ruby
125
+ Relation.remove order, user
126
+ ~~~
127
+
128
+ Removing a relationship does not delete either record.
129
+ If the relationship does not exist, nothing happens.
130
+
131
+ ### Raw API
132
+
133
+ The raw API operates directly on model names and record IDs,
134
+ without requiring the corresponding ActiveRecord records to exist.
135
+
136
+ ~~~ruby
137
+ Relation.add_raw "Order", 1, "User", 1
138
+ Relation.add_raw "Order", 1, "User", 2
139
+
140
+ Relation.references_raw "Order", 1, "User" # => [1, 2]
141
+ Relation.followers_raw "Order", "User", 2 # => [1]
142
+
143
+ Relation.remove_raw "Order", 1, "User", 2
144
+ ~~~
145
+
146
+ The raw API uses `Relation.remove_raw` to delete relationships
147
+ by model names and IDs,
148
+ while the object API uses `Relation.remove` to delete relationships
149
+ between ActiveRecord instances.
150
+
151
+ Unlike the object API, the raw API does not verify
152
+ whether referenced records exist.
153
+ You are responsible for maintaining data consistency.
154
+
155
+ ## Limitations
156
+
157
+ **Relation** provides a simpler abstraction than
158
+ conventional Rails associations.
159
+
160
+ - No association macros, proxies, or callbacks.
161
+ - No automatic association loading or eager loading.
162
+ - No nested attributes or dependent destruction.
163
+ - No database-level foreign key constraints.
164
+ - Only integer primary keys are supported by the object API.
165
+ - Model renaming may require updating stored model names.
166
+ - Bulk operations bypass ActiveRecord callbacks.
167
+ - The relationship table has no conventional primary key.
168
+
169
+ The application is responsible for maintaining referential integrity.
170
+
171
+ ### Dangling relationships
172
+
173
+ A relationship is dangling when either its source or target
174
+ record no longer exists.
175
+
176
+ Use `Relation.dangling` to identify dangling relationships:
177
+
178
+ ~~~ruby
179
+ Relation.dangling
180
+ # => {
181
+ # "User" => [3, 7],
182
+ # "Product" => [12]
183
+ # }
184
+ ~~~
185
+
186
+ Returns a hash mapping model names to IDs of records that no longer exist
187
+ but are still involved in stored relationships.
188
+
189
+ Use `Relation.remove_dangling` to remove relationships
190
+ involving missing records:
191
+
192
+ ~~~ruby
193
+ Relation.remove_dangling(Relation.dangling)
194
+ ~~~
195
+
196
+ Cleanup is not performed automatically
197
+ and remains the application's responsibility.
198
+
199
+ ## Compatibility
200
+
201
+ Version | Rails
202
+ :------ |:-------
203
+ 1.0.x | 8+
204
+ 0.5.x | 8
205
+ 0.4.x | 7
206
+ 0.1.1 | Older versions
207
+
208
+ Version 1.0 introduces the following breaking changes:
209
+
210
+ - `Relation.delete(x, y)` was renamed to `Relation.remove(x, y)`.
211
+ - `Relation.delete_raw(x, y)` was renamed to `Relation.remove_raw(x, y)`.
212
+ - `Relation.followers(Order, user)` changed
213
+ to `Relation.followers(user, Order)`.
214
+
215
+ ## License
216
+
217
+ Copyright (c) 2015-2026 Dittmar Krall.
218
+
219
+ Released under the [MIT license](https://opensource.org/licenses/MIT).
@@ -1,26 +1,45 @@
1
1
  class Relation < ActiveRecord::Base
2
- # dangling relations
2
+ # Returns missing record IDs grouped by polymorphic model name.
3
3
  def self.dangling
4
- names = Relation.pluck(:name).uniq
5
- models = []
6
- names.each { |name| models |= name.split(" ") }
7
- hsh = {}
8
- models.each do |class_name|
9
- klass = class_name.constantize
10
- ids = klass.pluck(:id)
11
- idx = Relation.where("name like ?", "#{class_name} %").pluck(:from_id)
12
- idy = Relation.where("name like ?", "% #{class_name}").pluck(:to_id)
13
- arr = (idx | idy) - ids
14
- hsh[class_name] = arr if arr.length.positive?
4
+ names = distinct.pluck(:from_name, :to_name).flatten.uniq
5
+
6
+ names.each_with_object({}) do |name, result|
7
+ klass = name.safe_constantize
8
+
9
+ next unless valid_model?(klass)
10
+
11
+ primary_key = klass.primary_key
12
+
13
+ from_ids = where(from_name: name)
14
+ .where.not(from_id: klass.select(primary_key))
15
+ .distinct
16
+ .pluck(:from_id)
17
+
18
+ to_ids = where(to_name: name)
19
+ .where.not(to_id: klass.select(primary_key))
20
+ .distinct
21
+ .pluck(:to_id)
22
+
23
+ ids = from_ids | to_ids
24
+
25
+ result[name] = ids if ids.any?
15
26
  end
16
- hsh
17
27
  end
18
28
 
19
- def self.remove_dangling(hsh)
20
- hsh.each do |name, arr|
21
- arr.each do |idx|
22
- Relation.where(from_id: idx).where("name like ?", "#{name} %").delete_all
23
- Relation.where(to_id: idx).where("name like ?", "% #{name}").delete_all
29
+ def self.remove_dangling(dangling)
30
+ raise ArgumentError, "expected a Hash" unless dangling.is_a?(Hash)
31
+
32
+ transaction do
33
+ dangling.each do |name, ids|
34
+ name = normalize_name(name)
35
+
36
+ raise ArgumentError, "IDs must be an Array" unless ids.is_a?(Array)
37
+
38
+ ids = ids.uniq
39
+ next if ids.empty?
40
+
41
+ where(from_name: name, from_id: ids).delete_all
42
+ where(to_name: name, to_id: ids).delete_all
24
43
  end
25
44
  end
26
45
  end
@@ -1,20 +1,54 @@
1
1
  class Relation < ActiveRecord::Base
2
- def self.add_raw(name, from_id, to_id)
3
- hsh = {name: name, from_id: from_id, to_id: to_id}
4
- # Relation.create!(hsh) if Relation.where(hsh).first.nil?
5
- Relation.create!(hsh) if Relation.where(hsh).count == 0
2
+ self.primary_key = nil
3
+
4
+ # Object API
5
+
6
+ # Adds a directed relationship from +from+ to +to+.
7
+ def self.add(from, to)
8
+ add_raw(*normalize(from, to))
9
+ end
10
+
11
+ def self.remove(from, to)
12
+ remove_raw(*normalize(from, to))
13
+ end
14
+
15
+ # Returns records of +kind+ referenced by +row+.
16
+ def self.references(row, kind)
17
+ klass, from_name, from_id = normalize_target(kind, row)
18
+
19
+ to_name = klass.polymorphic_name
20
+ ids = where(from_name:, from_id:, to_name:).select(:to_id)
21
+
22
+ klass.where(klass.primary_key => ids)
23
+ end
24
+
25
+ # Returns records of +kind+ that reference +row+.
26
+ def self.followers(row, kind)
27
+ klass, to_name, to_id = normalize_target(kind, row)
28
+
29
+ from_name = klass.polymorphic_name
30
+ ids = where(from_name:, to_name:, to_id:).select(:from_id)
31
+
32
+ klass.where(klass.primary_key => ids)
33
+ end
34
+
35
+ # Raw API operates on polymorphic model names and record IDs.
36
+
37
+ def self.add_raw(from_name, from_id, to_name, to_id)
38
+ create_or_find_by!(
39
+ normalize_attrs(from_name:, from_id:, to_name:, to_id:)
40
+ )
6
41
  end
7
42
 
8
- def self.delete_raw(name, from_id, to_id)
9
- hsh = {name: name, from_id: from_id, to_id: to_id}
10
- Relation.where(hsh).delete_all
43
+ def self.remove_raw(from_name, from_id, to_name, to_id)
44
+ where(normalize_attrs(from_name:, from_id:, to_name:, to_id:)).delete_all
11
45
  end
12
46
 
13
- def self.references_raw(name, from_id)
14
- Relation.where(name: name, from_id: from_id).pluck(:to_id)
47
+ def self.references_raw(from_name, from_id, to_name)
48
+ where(normalize_attrs(from_name:, from_id:, to_name:)).pluck(:to_id)
15
49
  end
16
50
 
17
- def self.followers_raw(name, to_id)
18
- Relation.where(name: name, to_id: to_id).pluck(:from_id)
51
+ def self.followers_raw(from_name, to_name, to_id)
52
+ where(normalize_attrs(from_name:, to_name:, to_id:)).pluck(:from_id)
19
53
  end
20
54
  end
@@ -0,0 +1,79 @@
1
+ class Relation < ActiveRecord::Base
2
+ def self.valid_model?(klass)
3
+ klass.is_a?(Class) &&
4
+ klass < ActiveRecord::Base &&
5
+ klass.name.present? &&
6
+ !klass.abstract_class? &&
7
+ klass.primary_key.present?
8
+ end
9
+
10
+ def self.normalize_kind(kind)
11
+ unless kind.is_a?(Class) || kind.is_a?(String) || kind.is_a?(Symbol)
12
+ raise ArgumentError, "kind must be a model class, string or symbol"
13
+ end
14
+
15
+ klass = kind.is_a?(Class) ? kind : kind.to_s.safe_constantize
16
+
17
+ unless valid_model?(klass)
18
+ raise ArgumentError,
19
+ "kind must be a named ActiveRecord model with a primary key"
20
+ end
21
+
22
+ klass
23
+ end
24
+
25
+ def self.normalize_name(name)
26
+ unless name.is_a?(String) || name.is_a?(Symbol)
27
+ raise ArgumentError, "model name must be a string or symbol"
28
+ end
29
+
30
+ name = name.to_s
31
+
32
+ raise ArgumentError, "model name cannot be blank" if name.blank?
33
+
34
+ name
35
+ end
36
+
37
+ def self.model_name_and_id(resource)
38
+ raise ArgumentError, "missing resource" unless resource
39
+ unless resource.is_a?(ActiveRecord::Base)
40
+ raise ArgumentError, "resource must be an ActiveRecord model"
41
+ end
42
+ unless resource.persisted?
43
+ raise ArgumentError, "resource must be persisted"
44
+ end
45
+
46
+ klass = resource.class
47
+ unless valid_model?(klass)
48
+ raise ArgumentError,
49
+ "resource must be a named ActiveRecord model with a primary key"
50
+ end
51
+
52
+ [klass.polymorphic_name, resource.id]
53
+ end
54
+
55
+ def self.normalize(from, to)
56
+ [*model_name_and_id(from), *model_name_and_id(to)]
57
+ end
58
+
59
+ def self.normalize_target(kind, row)
60
+ [normalize_kind(kind), *model_name_and_id(row)]
61
+ end
62
+
63
+ def self.normalize_attrs(attrs)
64
+ %i[from_id to_id].each do |key|
65
+ if attrs.key?(key) && attrs[key].nil?
66
+ raise ArgumentError, "#{key} cannot be nil"
67
+ end
68
+ end
69
+
70
+ attrs.merge(
71
+ from_name: normalize_name(attrs[:from_name]),
72
+ to_name: normalize_name(attrs[:to_name])
73
+ )
74
+ end
75
+
76
+ private_class_method :valid_model?, :model_name_and_id,
77
+ :normalize, :normalize_target,
78
+ :normalize_kind, :normalize_attrs, :normalize_name
79
+ end
@@ -1,12 +1,13 @@
1
1
  class CreateRelations < ActiveRecord::Migration[7.0]
2
2
  def change
3
3
  create_table :relations, id: false do |t|
4
- t.string :name
5
- t.references :from, null: false
6
- t.references :to, null: false
7
- t.timestamps
4
+ t.string :from_name, null: false
5
+ t.bigint :from_id, null: false
6
+ t.string :to_name, null: false
7
+ t.bigint :to_id, null: false
8
8
 
9
- t.index :name
9
+ t.index [:from_name, :from_id, :to_name, :to_id], unique: true
10
+ t.index [:to_name, :to_id, :from_name, :from_id]
10
11
  end
11
12
  end
12
13
  end
@@ -1,20 +1,12 @@
1
1
  # rubocop: disable all
2
2
 
3
3
  module ModRelation
4
- VERSION = "0.5.2" # 2026-01-01
4
+ VERSION = "1.0.1" # 2026-11-27
5
+ # VERSION = "0.5.3" # 2026-03-30
6
+ # VERSION = "0.5.2" # 2026-01-01
5
7
  # VERSION = "0.5.1" # 2025-10-29
6
8
  # VERSION = "0.5.0" # 2025-06-18
7
- # VERSION = "0.4.5" # 2024-10-21
8
- # VERSION = "0.4.4" # 2023-12-12
9
- # VERSION = "0.4.3" # 2023-04-16
10
- # VERSION = "0.4.2" # 2023-01-19
11
- # VERSION = "0.4.1" # 2023-01-18
12
- # VERSION = "0.4.0" # 2023-01-12
13
9
  # VERSION = "0.3.8" # 2021-06-22
14
- # VERSION = "0.3.7" # 2020-07-14
15
- # VERSION = "0.3.6" # 2020-04-27
16
- # VERSION = "0.3.5" # 2020-03-03
17
- # VERSION = "0.3.4" # 2019-10-04
18
10
  # VERSION = "0.3.3" # 2019-03-23
19
11
  # VERSION = "0.3.2" # 2019-03-05
20
12
  # VERSION = "0.3.1" # 2018-08-05
data/lib/relation.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  require "models/relation"
2
- require "models/relation_ext"
3
2
  require "models/dangling"
3
+ require "models/relation_private"
data/relation.gemspec CHANGED
@@ -3,12 +3,11 @@ require_relative "lib/relation/version"
3
3
  Gem::Specification.new do |s|
4
4
  s.name = "relation"
5
5
  s.version = ModRelation::VERSION
6
- s.summary = <<-END
7
- Rails gem adding relationships between ActiveRecord models.
8
- END
6
+ s.summary = "A lightweight relationship store for ActiveRecord models"
9
7
  s.description = <<-END
10
- A Rails gem that adds simple support for organizing ActiveRecord models.
11
- Relationships are stored in one additional database table.
8
+ Relation allows you to establish relationships between arbitrary
9
+ ActiveRecord records without adding foreign keys, association columns,
10
+ or dedicated join tables to their respective database tables.
12
11
  END
13
12
  s.authors = ["Dittmar Krall"]
14
13
  s.email = ["dittmar.krall@matiq.com"]
@@ -20,8 +19,11 @@ Gem::Specification.new do |s|
20
19
 
21
20
  s.files = `git ls-files`.split("\n")
22
21
  s.require_paths = ["lib", "app"]
23
- s.required_ruby_version = ">= 3"
22
+ s.required_ruby_version = ">= 3.2"
23
+
24
+ s.add_dependency "activerecord", ">= 8.0", "< 9.0"
24
25
 
26
+ s.add_development_dependency "rake"
25
27
  s.add_development_dependency "combustion"
26
28
  s.add_development_dependency "minitest"
27
29
  end