0

我今天开始学习 Rails,但不太确定它是如何工作的:

假设我有一家公司,该公司可能有许多子公司。

子公司是一家公司。出于显而易见的原因,一家公司不能成为自己的子公司。

子公司不能拥有同时是公司子公司的子公司

所以一个子公司也可以有子公司,所以它无限嵌套

我也不确定以下是子公司是公司

class Company < ActiveRecord::Base
    has_many :subsidiaries
end
class Subsidiary < ActiveRecord::Base
    belongs_to :companies
end

我确定这是错误的,只是在这里放一些东西

更新:

好的,所以我按照以下说明进行操作:

class Company < ActiveRecord::Base
    validates   :name, presence: true
    belongs_to :company
    has_many :subsidiaries, foreign_key: 'company_id', class_name: 'Company'
end

在我的一个模板中:

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

现在这是错误的,发生的事情是拥有子公司的人表明他们没有子公司,而那些是子公司的人则表明他们有子公司,所以基本上它现在显示其父母的,它的“孩子”

知道为什么会这样吗?

4

2 回答 2

1

What you want is a recursive self relation:

class Company < ActiveRecord::Base
    belongs_to :company
    has_many :subsidiaries, foreign_key: 'company_id', class_name: 'Company'
end

So, essentially, a company belongs to a company and has many companies. However, we have a special name for it's companies (subsidiaries), so we give it this "alias" by manually setting the relation. You might want to do the same for the "parent" company.

You would then use validations to check all those conditions.

于 2013-07-18T14:59:52.633 回答
1

I would use

class Company < ActiveRecord::Base
  has_many   :subsidiaries, class_name: 'Company', foreign_key: :parent_id
  belongs_to :parent, class_name: 'Company'
end

To use these relations you will need parent_id column in your table:

rails g migration add_parent_id_to_companies parent_id:ineteger
rake db:migrate

You would use like this:

          A
        /   \
       /     \
      B       C
     / \
    /   \
   D     E


A.subsidiaries => [B,C]
B.subsidiaries => [D,E]
C.subsidiaries => [] # actually a relation without results
B.parent => A
C.parent => A
A.parent => nil
D.parent => B
于 2013-07-18T15:00:03.433 回答