Ruby on rails Rails-如何列出每个对象';多对多关系中的对象是什么?
我有多个具有联接表的模型,我希望在控制器中实现这些项的列表Ruby on rails Rails-如何列出每个对象';多对多关系中的对象是什么?,ruby-on-rails,ruby,many-to-many,Ruby On Rails,Ruby,Many To Many,我有多个具有联接表的模型,我希望在控制器中实现这些项的列表 Customer <- many -> Products Products <- many -> Teams Products <- many -> Documents 客户产品 产品团队 产品文件 型号: class Customer < ActiveRecord::Base has_many :cstprd_relations has_many :products, :thr
Customer <- many -> Products
Products <- many -> Teams
Products <- many -> Documents
客户产品
产品团队
产品文件
型号:
class Customer < ActiveRecord::Base
has_many :cstprd_relations
has_many :products, :through => :cstprd_relations
end
class Product < ActiveRecord::Base
has_many :cstprd_relations
has_many :customers, :through => :cstprd_relations
has_many :teaprd_relations
has_many :teams, :through => :teaprd_relations
end
class Team < ActiveRecord::Base
has_many :teaprd_relations
has_many :products, :through => :teaprd_relations
end
class Document < ActiveRecord::Base
has_many :prddoc_relations
has_many :products, :through => :prddoc_relations
end
class客户:cstprd\U关系
结束
类产品:cstprd\U关系
有很多:教师关系
有很多:团队,:通过=>:teaprd\u关系
结束
类团队:teaprd\u关系
结束
类文档:prddoc\u关系
结束
例如,文档迁移:
class CreateDocuments < ActiveRecord::Migration
def change
create_table :documents do |t|
t.string :name
t.timestamps null: false
end
end
end
class AddDocumentRefToProducts < ActiveRecord::Migration
def change
add_reference :products, :document, index: true, foreign_key: true
end
end
class CreateDocuments
如何列出属于产品的唯一文档并将它们(文档)链接到团队
像这样:
客户1:
- “产品‘计算’的文档‘测试阶段1’由团队完成 “QA、测试团队、开发人员”
- “产品‘电话’的文档‘测试阶段2’由团队完成 “QA、TechSpec、营销团队”
- “产品‘应用’的文档‘安装指南’由团队‘开发人员,TechSpec’完成”
team_4_documents = Document.where(product_id: Team.find(4).products).all
(.find(4)这是一个使团队成为特定团队的示例)也许这段代码展示了它的样子
Product.all.each do | prod |
Document.products( prod.id ).teams.each do | team |
# generate message
end
end
或者基于文档
Document.where( :id => id ).each do | doc |
doc.products.each do | prod |
prod.teams.each do | team |
# generate you message
end
end
end
编辑
在评论中回答问题
Customer.all.each do | cust |
puts "Customer #{cust.name}"
cust.products.each do | prod |
prod.documents.each do | doc |
print "* Document #{doc.name} for product #{prod.name} is finished by teams "
puts "'" + prod.teams.map(&:name).join(', ') + "'"
end
end
end
但如何列出仅针对特定客户产品的文档?(它们不应重复)没有product_id之类的列。。。我认为只使用联接表是可能的?对不起,我错过了联接表。。。。也许这样就可以了:
team_4_documents=Document.joins(:prddoc_relations)。其中(prddoc_relations:{product_id:team.find(4.products})。全部
。。。