ruby - Rails: Many to many relation to self -


i having problems creating association: consider model "entry". want entries have many entries parents , want entries have many entries children. want realize relation via model called "association", here tried:

migration:

class createassociations < activerecord::migration[5.0]   def change     create_table :associations |t|       t.integer :parent_id       t.integer :child_id     end   end end 

association model:

class association < applicationrecord   belongs_to :parent, class_name: 'entry'   belongs_to :child, class_name: 'entry' end 

so far works. how use create 2 many-to-many relations on model itself?

class entry < applicationrecord   # has many parent entries of type entry via table associations , child_id   # has many child entries of type entry via table associations , parent_id end 

this should work:

class entry < applicationrecord   has_and_belongs_to_many :parents, class_name: 'entry', join_table: :associations, foreign_key: :child_id, association_foreign_key: :parent_id   has_and_belongs_to_many :children, class_name: 'entry', join_table: :associations, foreign_key: :parent_id, association_foreign_key: :child_id end 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -