No commit activity in last 3 years
No release in over 3 years
Instead of a many-to-many join table, serialize the ids into a JSON array.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.6
>= 0
>= 0
>= 0

Runtime

 Project Readme

ActiveRecord::JsonHasMany

Build Status Code Climate

Instead of keeping the foreign keys on the children, or in a many-to-many join table, let's keep them in a JSON array on the parent.

Usage

require "active_record/json_has_many"

ActiveRecord::Schema.define do
  create_table :parents do |t|
    t.text :child_ids
  end

  create_table :children
end

class Parent < ActiveRecord::Base
  json_has_many :children
end

This will add some familiar has_many-style methods:

parent.children? #=> false

parent.children = [Child.create!, Child.create!, Child.create!]
parent.children #=> [#<Child id: 1>, #<Child id: 2>, #<Child id: 3>]

parent.child_ids = [1,2]
parent.child_ids #=> [1,2]

parent.children? #=> true

It also adds a scope class method for implementing the inverse relationship on the child:

class Child
  def parents
    Parent.where_json_array_includes(child_ids: id)
  end
end

child = Child.create!
parent = Parent.create children: [child]
child.parents == [parent] #=> true

Requirements

  • Ruby 2.0+

Contributing

  1. Fork it ( https://github.com/[my-github-username]/active_record-json_has_many/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request