Rails模型has_many [英] Rails models has_many

查看:116
本文介绍了Rails模型has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始学习课程,不太确定如何工作:

Im starting to learn rails today and not quite sure how this would work:

说我有一个公司,公司可能有很多子公司。

Lets say I have a Company, the company may have many subsidiaries.

子公司是一家公司。
一个公司不可能是自己的subi
日记显而易见的原因。

A subsidiary is a Company. A company cannot be its own subsi diary for obvious reasons.

子公司不能有子公司也是公司的子公司

A subsidiary cannot have a subsidiary that is also a subsidiary of the company

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

So a subsidiary can also have subsidiaries, so its unlimitedly nested

下面还不能确定的是子公司是一家公司

what im also not sure about below is that a subsidiary is a company

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

我确定这是不正确,只是把东西放在这里

Im sure this is so wrong, just putting something in here

更新:

按照以下说明进行操作:

Ok, so I followed the instructions below like this:

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 %>

现在这显示错误,发生什么事情是与子公司的Ones表示他们没有子公司,作为子公司的子公司显示他们有子公司,其基本上是显示其父母现在,其孩子

Now this is show wrong, what happens is that the Ones with subsidiaries shows they have no subsidiaries and the ones who are subsidiaries shows they have subsidiaries, SO basicly its showing its parent's now, its "children"

任何想法为什么会发生这种情况?

ANy idea why this happens?

推荐答案

我将使用

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

要使用这些关系,您将需要表中的 parent_id 列:

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

你可以这样使用:

          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

这篇关于Rails模型has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆