I have two models Type and Activity. Type has_many
activities and Activity has_many
types. To do this I used the has_many :through
thing. This is how it looks like
Activity
has_many :typeitems
has_many :types, :through => :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
When I went into rails console and typed types.activity
I got a nil which means I will get a single object. Should I change the belongs_to
in Type model to has_many
.But then it's back to many-to-many
. There should be a way.
I looked at the docs and found 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.
I am not using it now but I might want to in the future.
Both sides need a has_many :through
:
Activity
has_many :typeitems
has_many :types, :through => :typeitem
Typeitem
belongs_to :activity
belongs_to :type
Type
has_many :typeitems
has_many :activities, through: :typeitems
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.