简体   繁体   English

Ruby on Rails多对多

[英]Ruby on rails many-to-many

I have two models Type and Activity. 我有两个模型Type和Activity。 Type has_many activities and Activity has_many types. 类型has_many活动和Activity has_many类型。 To do this I used the has_many :through thing. 为此,我使用了has_many :through东西。 This is how it looks like 看起来像这样

Activity 活动

has_many :typeitems
has_many :types, :through => :typeitem

Typeitem Typeitem

belongs_to :activity
belongs_to :type

Type 类型

has_many :typeitems
belongs_to :activity

This does not feel right though. 但是,这感觉不对。 I would want to query 2 things 我想查询2件事

  1. Activities of a particular type 特定类型的活动
  2. Types of a particular activity 特定活动的类型

When I went into rails console and typed types.activity I got a nil which means I will get a single object. 当我进入Rails控制台并键入types.activity我得到了nil,这意味着我将得到一个对象。 Should I change the belongs_to in Type model to has_many .But then it's back to many-to-many . 我是否应该将Type模型中的belongs_to更改为has_many但随后又回到many-to-many There should be a way. 应该有办法。

I looked at the docs and found has_and_belongs_to_many . 我看了看文档,发现has_and_belongs_to_many I also read this 我也读过

You should use has_many :through if you need validations, callbacks, or extra attributes on the join model. 如果需要在连接模型上进行验证,回调或其他属性,则应使用has_many:through。

I am not using it now but I might want to in the future. 我现在不使用它,但将来可能会使用。

Both sides need a has_many :through : 双方都需要一个has_many :through

Activity 活动

has_many :typeitems
has_many :types, :through => :typeitem

Typeitem Typeitem

belongs_to :activity
belongs_to :type

Type 类型

has_many :typeitems
has_many :activities, through: :typeitems

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM