自引用关联问题

时间:2010-09-14 08:45:48

标签: ruby-on-rails activerecord associations

我有下一个型号:

create_table :categories do |t|
  t.integer :category_id
  t.integer :language_id
  t.timestamps
end

create_table :category_localizated_categories, :force => true do |t|
  t.column :category_id, :integer
  t.column :localizated_category_id, :integer
end

class Category < ActiveRecord::Base
  has_many :category_localizated_categories
  has_many :localizated_categories, :through => :category_localizated_categories
end

class CategoryLocalizatedCategory < ActiveRecord::Base
   belongs_to :category
   belongs_to :localizated_category
end

我能做到:

category1 = Category.create :language_id => 1
category2 = category1.localizated_categories.create :language_id => 2

在DB中创建了2个类别,但未创建关联:

category.localizated_categories
[]

可能是什么问题?感谢。

2 个答案:

答案 0 :(得分:3)

为什么不选择更简单的自我指涉?

class Category < ActiveRecord::Base
  belongs_to :base_category, :class_name => "Category"
  has_many :localized_categories, :class_name => "Category", :inverse_of => :base_category

  scope :base, where(:base_category_id => nil)
  scope :localized, where("base_category_id NOT NULL")
  …
end

答案 1 :(得分:0)

class Category < ActiveRecord::Base
  has_many :category_localizated_categories
  has_many :localizated_categories, :through => :category_localizated_categories
  accepts_nested_attributes_for :category_localizated_categories
end

我认为你需要嵌套模型:

http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes