大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – has_many:通过has_and_belongs_to_many关联,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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?
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_items和food_item.places都可以完美地工作,以及更简单的协会.仅供参考,这是我的架构,以显示所有外键的位置:
create_table "food_categories",:force => true do |t| t.String "name" t.Integer "place_id" t.datetiR_843_11845@e "created_at" t.datetiR_843_11845@e "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.datetiR_843_11845@e "created_at" t.datetiR_843_11845@e "updated_at" end create_table "food_items",:force => true do |t| t.String "name" t.datetiR_843_11845@e "created_at" t.datetiR_843_11845@e "updated_at" end create_table "places",:force => true do |t| t.String "name" t.datetiR_843_11845@e "created_at" t.datetiR_843_11845@e "updated_at" end
希望这可以帮助!
更新:这个问题最近出现了几次.我写了一篇文章,nesting your has_many :through relationships,详细解释.它甚至在GitHub上有一个附带的示例应用程序来下载和玩.
以上是大佬教程为你收集整理的ruby-on-rails – has_many:通过has_and_belongs_to_many关联全部内容,希望文章能够帮你解决ruby-on-rails – has_many:通过has_and_belongs_to_many关联所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。