ruby - 如果以及如何在 ActiveRecord 中使用 has_and_belongs_to_many 关联
问题描述
尝试创建一个域,用户可以在其中创建咖啡和混合物列表。一种混合物有许多咖啡,一种咖啡有许多混合物。这是我到目前为止所拥有的:
class User < ActiveRecord::Base
has_many :roasts
has_many :blends, :through => :roasts
class Roast < ActiveRecord::Base
belongs_to :user
# TODO: associate roasts with blends
class Blend < ActiveRecord::Base
# TODO: associate blends with roasts
我如何建立这种关系?我需要某种连接表吗?
解决方案
你好!我认为您可以像下面的代码块一样定义关联。
class User < ActiveRecord::Base
has_many :blend_and_roasts
has_many :blends, through: :blend_and_roasts
has_many :roasts, through: :blend_and_roasts
class Roast < ActiveRecord::Base
has_many :blend_and_roasts
has_many :blends, through: :blend_and_roasts
class Blend < ActiveRecord::Base
has_many :blend_and_roasts
has_many :roasts, through: :blend_and_roasts
快乐编码!
推荐阅读
- brython - 在 Object._b_.NotImplementedError.$factory 处出错(使用 Brython 在 $make_exc 处进行评估
- mongodb - 如何在 MongoDB 中获取具有最小值的文档?
- c - C中简单线程池和TCP监听器的问题
- sql-server - T-SQL 计算层次结构/父级
- nginx - Nginx 从同一 IP 地址上的另一个端口提供 Iframe
- spring - EhCacheManager bean 总是返回 Null
- node.js - “请求”类型上不存在属性“版本”
' - python - Python 3.7 - 打印 NumPy 数组列表在实际数组前面打印“数组”。为什么?
- python - pytest缓存机制说明及示例
- node.js - 如何使用nodejs在mongoose的另一个数组中拉取或删除数组的元素?