I am very new to Rails. After skimming through the documentation over
the last several days, I’m struggling with the appropriate use of
belongs_to. My main question is whether a model can have several
belongs_to declarations. I have not seen any examples online show that
usage. If it can, then I would like to know if it’s poor form or what
the best practices are around it. The documentation says that the
foreign key should be in the table that belongs_to the linked table so
that the linked table data is available via the object model. (i.e. if
system belongs_to address then you would have a foreign key
system.address_id so that you can do system.address.state or
system.address.zip, etc.
But if I have data in several other tables that I wish to access this
way, it would require several belongs_to declarations in the same model.
For my circumstances I have a system (represents a computer) table that
is linked to several other small tables. I want all the data in these
other tables to be available from the system object.
I have this:
class System < ActiveRecord::Base
belongs_to :department
belongs_to :address
belongs_to :operatingsystem
has_many :oldnames
end
class Department < ActiveRecord::Base
has_many :systems
has_many :people
end
class Address < ActiveRecord::Base
has_many :systems
has_many :people
end
class Oldname < ActiveRecord::Base
belongs_to :system
end
class Operatingsystem < ActiveRecord::Base
has_many :systems
end
class Person < ActiveRecord::Base
belongs_to :department
belongs_to :address
end
You’ll also notice that Person belongs_to Address and Department the
same way System does. Is this allowable? I have done this because I
have several thousand systems and several thousand people but only 25
addresses (locations). Same thing with Operatingsystems, I have several
thousand systems but only 8 or nine operating systems.
Any peer review the community can provide would be much appreciated.
One last question; I have a table of old hostnames (Oldnames). Oldname
belongs to System and System has_many Oldnames. Since system doesn’t
belong_to oldnames ,what’s the easiest way to fetch a System’s
collection of Oldnames?
Thanks for the help!
- Don