1
我有三個模型,我嘗試設置:位置/場所,類別和鄰域。如何爲此模式建立Rails關聯
位置必須具有父類別和子類別,而其鄰居是可選的。在類別模型中,有頂級類別或子類別。
鑑於上述情況,這是定義模型關聯的正確方法嗎?
class Location < ActiveRecord::Base
attr_accessible # location-specific columns
belongs_to :category
belongs_to :parent_category, :class_name => "Category"
belongs_to :neighborhood
end
class Category < ActiveRecord::Base
has_many :locations
has_many :subcategories, :class_name => "Category", :foreign_key => "parent_category_id"
belongs_to :parent_category, :class_name => "Category"
end
class Neighborhood < ActiveRecord::Base
has_many :locations
end
(實際上,閱讀更合適Rails Guide後,它看起來像多態關聯可能更合適呢?)
我一直沒能在代碼來檢查這個建議,但您的邏輯是有道理的。一旦我終於可以坐下來讓我的環境繼續運行,我可能還會有更多的問題...... – oohaba