I'm using Rails 3.0.1/Ruby 1.9.2
I have two tables: Product
and Category
.
These are the models:
class Product < ActiveRecord::Base
belo开发者_如何学Gongs_to :parent_category, :class_name => "Category"
end
class Category < ActiveRecord::Base
has_many :products
end
So I want to access the category of the product by calling product.parent_category
, and get all products from a certain category by calling category.products
.
But this doesn't work.
Rails raises an exception when I do category.products
column products.category_id does not exist
It tries to find the category_id
column, but I have a parent_category_id
column in my table and I want to use it.
How can I fix this?
Try this:
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
class Product < ActiveRecord::Base
belongs_to :parent_category, :class_name => "Category", :foreign_key => "parent_category_id"
end
精彩评论