【问题标题】:Connect the relationship between category,subcategory and gig连接类别、子类别和演出之间的关系
【发布时间】:2015-04-02 12:15:18
【问题描述】:

我的应用程序有类别,而不是子类别,而不是 gigs

我的控制器文件中有 gigs_controller.rb

还有 category.rb、subcategory.rb、gig.rb 在我的模型文件中。

按照 category=subcategory=gig 的原则,我如何建立它们之间的联系(gig 我的意思是我有很多小添加)

在Category.rb模型中说的对吗

class Category < ActiveRecord::Base
  has_many :subcategories
end

在我的子类别模型中

class Subcategory < ActiveRecord::Base
  belongs_to :category
end

在我的 Gig.rb 中

class Gig < ActiveRecord::Base
  belongs_to :user
  belongs_to :category # I also need here to be belongs_to :subcategory,how do i do that?
end

我应该为类别和子类别创建一个控制器吗?你会怎么做。 感谢您的支持,希望我的问题也能帮助到其他人。

【问题讨论】:

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


    【解决方案1】:
    class Category < ActiveRecord::Base
      has_many :subcategories
    end
    
    
    class Subcategory < ActiveRecord::Base
      belongs_to :category
      has_many :gigs
    end
    
    
    class Gig < ActiveRecord::Base
      belongs_to :user
      belongs_to :subcategory
    end
    

    【讨论】:

    • 我刚刚在 Rails 控制台中尝试了 "category".pluralize,它起作用了,但是当我执行 "subcategory".pluralize 时,它​​给出了一个错误。是否会影响上述关系?我应该将子类别模型编辑为 sub_category 吗?
    • 当我运行"category".pluralize 时,我得到categories。当我运行"subcategory".pluralize 时,我得到subcategories
    • 非常感谢!)您在 Gig.rb 中的回答中说,belongs_to :sub_category,我可以说belongs_to :subcategory 吗?你为什么使用下划线''_''行?对于子类别
    • 我打错了sry
    【解决方案2】:

    是的你可以在没有控制器的情况下在模型中使用 has_many。因为 has_many 使用表的名称。

    class Gig &lt; ActiveRecord::Base

    belongs_to :user

    belongs_to :subcategory

    end

    class Category &lt; ActiveRecord::Base

    has_many :subcategories

    end

    class Subcategory &lt; ActiveRecord::Base

    belongs_to :category

    has_many :gigs

    end

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 2013-02-15
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多