Reputation: 498
Rails newbie, so bear with me here. I need advice on how to properly set up the active record associations between 2 of my models.
As it stands right now, I have a User model. A User has_many Contacts. And a User has_many Posts. Simply put:
class User < ApplicationRecord
has_many :posts, dependent: :destroy
has_many :contacts, dependent: :destroy
class Contact < ApplicationRecord
belongs_to :user
class Post < ApplicationRecord
belongs_to :user
A user can send a post to one or more of their contacts (while that action is just something that triggers an email, I need to be able to track and display which contacts they've sent each post to). They can send a Post to many Contacts, and they may (over time) send each Contact more than 1 Post.
I'm a little uncertain how to associate Post and Contacts. Is it just a simple Post has_many Contacts (or vice versa)? Or should it be that a Post has_many Contacts THROUGH a User?
While I'm normally one who learns by trial and error, this is one of those situations where I'm worried if I go to far down the wrong path here, I'll figure it out so late that it'll be painful to undo - so thanks for any advice.
I'm using Rails 5 for what it's worth.
Upvotes: 0
Views: 73
Reputation: 26788
you don't necessarily need a join between Post
and Contacts
, i.e. you could write @post.user.contacts
or @contact.user.posts
,though it depends on your use-case.
But say you did want to create an association for Post
to get all the comments of the same user. You could write:
class Post < ActiveRecord::Base
has_many :contacts_of_user, through: :user, source: :contacts
end
You can use this same logic to implement contact.posts
as well.
Upvotes: 1
Reputation: 10472
What you are looking for is a many-to-many relationship. Since a post can be associated with many contacts, and a contact can be associated with many posts.
Here is a great read for the many-to-many relationship
Basically, you will be created a association table to help link the post and contacts table.
class Contact < ApplicationRecord
belongs_to :user
has_many :posts, through: post_contact
class Post < ApplicationRecord
belongs_to :user
has_many :contacts, throught: post_contact
You will be created a new join table called post_contact (or whatever you want) and that table provides the association between posts and contacts.
Hope this helps.
Upvotes: 1