2010-11-05 70 views
0

我用Rails 3.0.1/1.9.2红宝石Rails的关系不工作

我有两个表:ProductCategory

这些机型:

class Product < ActiveRecord::Base 
    belongs_to :parent_category, :class_name => "Category" 
end 

class Category < ActiveRecord::Base 
    has_many :products 
end 

所以,我想通过调用product.parent_category访问产品的类别,并通过调用category.products得到某一类的所有产品。

但这不起作用。

的Rails抛出一个异常,当我做category.products

column products.category_id does not exist 

它试图找到category_id列,但我在我的表有parent_category_id列,我想使用它。

我该如何解决这个问题?

+1

应该不是分类模型 “have_many:产品”? – 2010-11-05 15:52:06

+0

@Nate,你是对的。这是一个错字。固定。 – Alex 2010-11-05 16:36:37

+0

我的评论中有一个错字。哈! “has_many:products” – 2010-11-05 17:27:10

回答

1

试试这个:

class Product < ActiveRecord::Base 
    belongs_to :parent_category, :class_name => "Category" 
end 

class Category < ActiveRecord::Base 
    has_many :products, :foreign_key => :parent_category_id 
end 
1
class Product < ActiveRecord::Base 
    belongs_to :parent_category, :class_name => "Category", :foreign_key => "parent_category_id" 
end 
+0

谢谢,但这不能解决它。同样的错误... – Alex 2010-11-05 15:08:51