0

它已經將近一個星期,因爲我試圖找到一個解決我的困惑......這就是:3個或更多模型關聯的混亂在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。但我想玩SINGULAR對象,而不是數組。 A Program只有一個Subcategory和只有一個Category。我只是使用連接表來連接這三個連接。例如,目前我可以訪問program.program_categories[0].title,但我想訪問它,例如program.program_category

我怎樣才能'has_many:通過能力,但has_one的單一用法慣例都在一起? :|

P.S:我之前的問題也是關於這種情況,但我決定從頭開始學習關於協會的哲學。如果你想這樣你可以檢查我以前的帖子在這裏:How to access associated model through another model in Rails?

回答

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」你也可以得到所有子類別(任何級別),所有supercategories等

在你跳過子目錄模型這種情況下,因爲它僅僅是一個深度= 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 

樹贏!

+0

belongs_to:通過?? – scaryguy

+0

uhm ....代表:類別,:to =>:子類別 – rewritten

+0

不當......當我嘗試訪問program.program_category時,出現此錯誤:'NoMethodError:undefined method' ... By方式,你的第二個建議是有道理的。事實上,我只是在尋找能夠給我想要的東西。不管它是什麼。你能建議關於那些樹的東西的任何資源? – scaryguy