ruby on rails - How do I create a self join item when it also belongs to another model? -
i’m trying make self join relation model named: subsystem. in case subsystem represents java package, class or method. i’ve read rails documentation saw use this:
class subsystem < activerecord::base has_many :child_subsystems, class_name: "subsystem", foreign_key: "parent_id" belongs_to :parent, class_name: "subsystem" end
i looked @ couple examples in cases “create part” not described. problem i’m looking best way create subsystems, because: subsystem model belongs project. right create subsystems like:
project.subsystems.create(params)
i hope image make’s better understand. project, can have 0 multpiple subsystems, , every subsystem can have 0 multiple subsystems.
i’ve seen examples of making self join, people created item relation build, i’m not sure how combine existing create: project.subsystems.create.
can me out? in advance!
the way created self join association spot on.
if want create subsystem belongs project can project.subsystems.create(...)
, if want create subsystem belonging subsystem can subsystem.child_subsystems.create(..)
. call name of association defined in model (pluralised has many associations).
the difference between build , create methods build calls new
whereas create calls new
, save
. when create or build instances associated other instances defined in models, returned objects contain foreign keys of records built or created from.
Comments
Post a Comment