简体   繁体   中英

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?

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.

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.

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.

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