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 t开发者_如何学Gohere 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.
精彩评论