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
belongs_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?
class Product < ActiveRecord::Base
belongs_to :parent_category, :class_name => "Category", :foreign_key => "parent_category_id"
end
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.