0

自从我试图找到解决我的困惑的方法以来已经快一个星期了......这里是:

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

让我们更清楚一点:

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

我希望能够将这些模型中的每一个相互关联。我有我想做的事情,特别是多对多关联。我有一个categories_navigationJOIN 模型/表,我所有的其他表都连接到它。通过这种方式,我可以访问所有这些模型的所有字段。

但...

如你所知,has_many :through风格联想总是复数的。没有诸如 has_one :through 或 belongs_to through 之类的东西。但我想玩 SINGULAR 对象,而不是数组。AProgram只有一个Subcategory,只有一个Category。我只是使用连接表来仅在这三个之间建立连接。例如,目前我可以访问program.program_categories[0].title但我想访问它program.program_category,例如。

我怎样才能同时拥有 'has_many :through 的能力但 has_one 的单一用法约定?:|

PS:我之前的问题也是关于这种情况的,但我决定从头开始学习联想哲学。如果你愿意,可以在这里查看我之前的帖子:如何通过 Rails 中的另一个模型访问关联模型?

4

1 回答 1

0

为什么要使用与您有直接关系的连接表?最后,一个程序属于一个子类别,而子类别又属于一个类别。所以不需要连接表。

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

树赢!

于 2012-09-28T16:08:09.983 回答