我试图在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
Run Code Online (Sandbox Code Playgroud)
但调用实例方法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))
Run Code Online (Sandbox Code Playgroud)
这很有道理 - 因为FoodItem和FoodCategory上的HABTM我有一个名为的映射表food_categories_food_items.
我有什么做的就是some_food_item.places要正确对待地方了通过映射表,而不是寻找一个food_item_id在 …