繁体   English   中英

Rails出现3个或更多模型关联混乱

[英]3 or more model association confusion at Rails

自从我试图找到解决困惑的方法以来,已经过去了将近一周的时间了:这是:

我有一个Program模型。 我有一个ProgramCategory模型。 我有一个ProgramSubcategory模型。

让我们更清楚一点:

ProgramCategory ======> Shows, Movies, 
ProgramSubcategory ===> Featured Shows, Action Movies
Program ==============> Lost, Dexter, Game of Thrones etc...

我希望能够将这些模型彼此关联。 我有我想做的事情,尤其是与多对多关联时。 我有一个categories_navigation JOIN模型/表和所有我的其他表连接到它。 通过这种方式,我可以访问所有这些模型的所有字段。

但...

如您所知, has_many :through样式关联始终是复数形式。 没有诸如has_one:through或belongs_to through之类的东西。 但是我想玩单个对象,而不是数组。 一个Program只有一个Subcategory和一个Category 我只是使用一个连接表来仅在这3个表之间建立连接。例如,目前,我可以访问program.program_categories[0].title但是我想像program.program_category这样访问它。

我如何才能拥有“ has_many:through”功能,却又拥有has_one的单一用法约定? :|

PS:我之前的问题也是关于这种情况的,但是我决定从头开始,学习协会的哲学。 如果需要,您可以在这里查看我的上一篇文章: 如何通过Rails中的另一个模型访问关联的模型?

为什么在联接表中有直接关系? 最后,程序属于一个子类别,而子类别又属于一个类别。 因此,不需要联接表。

class Program < ActiveRecord::Base
  belongs_to :subcategory   # references the "subcategory_id" in the table
  # belongs_to :category, :through => :subcategory
  delegate :category, :to => :subcategory
end

class Subcategory < ActiveRecord::Base
  has_many :programs
  belongs_to :category    # references the "category_id" in the table
end

class Category < ActiveRecord::Base
  has_many :subcategories
  has_many :programs, :through => :subcategories
end

另一个观点是使类别成为一棵树,因此您不需要“级别2”类别的其他模型,您可以添加任意数量的级别。 如果您使用“ closure_tree”之类的树实现,则还可以获取所有子类别(处于任何级别),所有超级类别等

在这种情况下,您将跳过Subcategory模型,因为它只是depth = 2的类别

class Program < ActiveRecord::Base
  belongs_to :category   # references the "category_id" in the table

  scope :in_categories, lambda do |cats|
    where(:category_id => cats)  # accepts one or an array of either integers or Categories
  end
end

class Category < ActiveRecord::Base
  acts_as_tree
  has_many :programs
end

只是有关如何使用树按类别过滤的示例。 假设您有一个选择框,然后从中选择一个类别。 您想要检索与其任何子类别相对应的所有对象,而不仅仅是类别。

class ProgramsController < ApplicationController

  def index

    @programs = Program.scoped
    if params[:category].present?
      category = Category.find(params[:category])
      @programs = @programs.in_categories(category.descendant_ids + [category.id])
    end

  end

end

树赢了!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM