database design - Rails models has_many -


im starting learn rails today , not quite sure how work:

lets have company, company may have many subsidiaries.

a subsidiary company. company cannot own subsi diary obvious reasons.

a subsidiary cannot have subsidiary subsidiary of company

so subsidiary can have subsidiaries, unlimitedly nested

what im not sure below subsidiary company

class company < activerecord::base     has_many :subsidiaries end class subsidiary < activerecord::base     belongs_to :companies end 

im sure wrong, putting in here

update:

ok, followed instructions below this:

class company < activerecord::base     validates   :name, presence: true     belongs_to :company     has_many :subsidiaries, foreign_key: 'company_id', class_name: 'company' end 

in 1 of templates:

<% @companies.each |company| %>     <li><%= link_to  "#{company.name} #{company.subsidiaries.length > 0 ? "(#{company.subsidiaries.length} subsidiaries)" :"" }", company_path(@company, :id => company.id) %></td> <% end %> 

now show wrong, happens ones subsidiaries shows have no subsidiaries , ones subsidiaries shows have subsidiaries, basicly showing parent's now, "children"

any idea why happens?

what want recursive self relation:

class company < activerecord::base     belongs_to :company     has_many :subsidiaries, foreign_key: 'company_id', class_name: 'company' end 

so, essentially, company belongs company , has many companies. however, have special name it's companies (subsidiaries), give "alias" manually setting relation. might want same "parent" company.

you use validations check conditions.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -