开发者

Rails relationships don't work

开发者 https://www.devze.com 2023-01-23 21:44 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消