Afsane Fadaei Afsane Fadaei - 19 days ago 6
Ruby Question

Self association in rails to keep track of related records

I have a model named Letter and an other one named LetterTracking :

class Letter < ApplicationRecord
has_many :letter_trackings, as: :trackable
end


and:

class LetterTracking < ApplicationRecord
belongs_to :letter
has_many :letter_trackings, as: :trackable
end


this is my create table migration for Letter Tracking:

class CreateLetterTrackings < ActiveRecord::Migration[5.0]
def change
create_table :letter_trackings do |t|
t.integer :trackable_id, default: 0, null: false, unique: true
t.string :trackable_type
t.text :paraph
t.string :status
t.string :assignee
t.belongs_to :letter
t.timestamps
end
end
end


as you can see in below screen shots when I select a tracking record for the second tracking the relation is ok but when ever I add the third letter tracking the second one relation removes and the last one keeps the association.
What I want is to keep the letter tracking in each record not by the last one. I mean some thing like nested records in which I can keep the related records.
any Idea ?
Thank you
enter image description here
enter image description here

Answer

First of all as a second thought the polymorphic relation seems quite useless for keeping track in this case. The thing which fits best here is tree based relation I suppose. this is my LetterTracking.rb

class LetterTracking < ApplicationRecord
    belongs_to :letter
    has_many :children, class_name: "LetterTracking", foreign_key: "parent_id"                             
    belongs_to :parent, class_name: "LetterTracking"
end

and this is my letter.rb

class Letter < ApplicationRecord
    has_many :letter_trackings
end

and finaly the LetterTrackings Migration:

class CreateLetterTrackings < ActiveRecord::Migration[5.0]
  def change
    create_table :letter_trackings do |t|
      t.references :parent, index: true
      t.text     :paraph
      t.string   :status
      t.string   :assignee
      t.belongs_to :letter, index: true
      t.timestamps
    end
  end
end

Now I can have the records of the lettertrackings join together like a tree while keeping the letter id in every single record! Yep :)