Reputation: 27114
I would like my User
to be associated with specific Email
's, when they receive them.
In this way, I can look up an array of what emails they have received.
Originally, I was thinking of just creating a string field for the User table, and adding the unique ID to the array..
User.find(x).received_emails << Email.find(x).id
But there may be a better way to do this with associating models.
Recommendations?
Upvotes: 0
Views: 610
Reputation: 27779
class Email < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :received_emails, :class_name => 'Email'
end
User.find(x).received_emails << Email.find(y)
This approach would require adding a user_id
column to the Email table.
You probably want to change this to a many-to-many association by adding a join table such as user_emails with a UserEmail model. That table would have user_id
and email_id
columns.
Upvotes: 2
Reputation:
You should check this link out:
It sounds like you're talking about a one to many sort of thing. If you use the association mechanism you'll get all the behavior you want, basically for free.
Upvotes: 3