我有下面的模型:
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在数据库中创建了两个类别,但没有创建关联:
category.localizated_categories
[]可能的问题是什么?谢谢。
发布于 2011-01-28 05:15:28
为什么你不去找一个更简单的自我参照的联想呢?
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发布于 2010-09-14 16:49:47
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
https://stackoverflow.com/questions/3707307
复制相似问题