我正在一个Ruby on Rails项目中尝试做以下事情:
class FoodItem < ActiveRecord::Base
has_and_belongs_to_many :food_categories
has_many :places, :through => :food_categories
end
class FoodCategory < ActiveRecord::Base
has_and_belongs_to_many :food_items
belongs_to :place
end
class Place < ActiveRecord::Base
has_many :food_categories
has_many :food_items, :through => :food_category
end
但是调用实例方法some_food_item.places
会给我以下错误:
ActiveRecord::StatementInvalid: PGError: ERROR: column
food_categories.food_item_id does not exist
LINE 1: ...laces".id = "food_categories".place_id WHERE (("food_cate...
: SELECT "places".* FROM "places" INNER JOIN "food_categories" ON "places".id = "food_categories".place_id WHERE (("food_categories".food_item_id = 1))
这是很有道理的 - 因为在FoodItem和FoodCategory上有HABTM,所以我有一个名为food_categories_food_items
的映射表。
要让some_food_item.places
通过映射表正确查找地点,而不是在food_categories
表中查找food_item_id
,我需要做什么?