Trip
Trip

Reputation: 27114

Best way to create an association in Rails

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

Answers (2)

Mori
Mori

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

user483040
user483040

Reputation:

You should check this link out:

Rails association guide

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

Related Questions