gpt4 book ai didi

ruby-on-rails - has_many :through a has_and_belongs_to_many association

转载 作者:行者123 更新时间:2023-12-03 16:10:16 25 4
gpt4 key购买 nike

我正在尝试在 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_item_idfood_categories table ?

最佳答案

我的第一个答案版本不正确,但这个版本完美无缺。我第一次犯了几个错别字(实际上没有创建要测试的应用程序的危险),但这次我进行了验证。并且需要一个插件,但这很容易。首先,安装插件:

script/plugin install git://github.com/ianwhite/nested_has_many_through.git

这将安装 Ian White 的解决方法,并且可以无缝运行。现在模型,直接从我设置的测试应用程序复制以使其正常工作:
class FoodItem < ActiveRecord::Base
has_many :food_category_items
has_many :food_categories, :through => :food_category_items
has_many :places, :through => :food_categories
end

class FoodCategory < ActiveRecord::Base
has_many :food_category_items
has_many :food_items, :through => :food_category_items
belongs_to :place
end

class FoodCategoryItem < ActiveRecord::Base
belongs_to :food_item
belongs_to :food_category
end

class Place < ActiveRecord::Base
has_many :food_categories
has_many :food_category_items, :through => :food_categories
has_many :food_items, :through => :food_category_items
end

现在“远”关联也能正常工作。 place_instance.food_itemsfood_item.places两者都完美无缺,以及所涉及的更简单的关联。仅供引用,这是我的模式,用于显示所有外键的去向:
create_table "food_categories", :force => true do |t|
t.string "name"
t.integer "place_id"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "food_category_items", :force => true do |t|
t.string "name"
t.integer "food_item_id"
t.integer "food_category_id"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "food_items", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "places", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end

希望这可以帮助!

更新:这个问题最近出现了几次。我写了一篇文章, nesting your has_many :through relationships ,详细解释。它甚至在 GitHub 上还有一个随附的示例应用程序可供下载和使用。

关于ruby-on-rails - has_many :through a has_and_belongs_to_many association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2150582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com