【问题标题】:How to add subcategory to category Model如何将子类别添加到类别模型
【发布时间】:2015-06-07 23:26:01
【问题描述】:

我的网站有 Categories=>Subcategories=>Gigs (#by gig i mean lots of adds)

添加类别很简单,我打开rails控制台,然后输入

Category.create(name: "Programming & Tech") #there are 6 categories

当我输入 Category.all 时,我会返回我创建的所有 6 个类别。

问题:

如何为 6 个类别中的每一个添加 5 个不同的 子类别? 例如:对于编程和技术类别将有 2 个子类别,wordpress 和 ruby​​ on rails..et。

注意:所有的(belongs_to,has_many,migrations,它们的关联是有序的)

感谢您的宝贵时间。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller model


    【解决方案1】:

    使用 STI(单表继承)

    ancestry gem 非常适合这项任务。

    【讨论】:

      【解决方案2】:

      假设您希望每个类别中都有相同的 6 个子类别,您可以键入

      Category.all.each do |c|
        %w(high low extreme xl xxl xxs).each do |subcat|
          c.subcategories.create(name: subcat)
        end
      end
      

      Rails Guides

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多