[英]Best way to create an association in Rails
I would like my User
to be associated with specific Email
's, when they receive them.我希望我的
User
在收到它们时与特定的Email
相关联。
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 表创建一个字符串字段,并将唯一 ID 添加到数组中。
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 Rails 协会指南
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.这种方法需要在 Email 表中添加一个
user_id
列。
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.您可能希望通过添加连接表(例如 user_emails 和 UserEmail model)来将其更改为多对多关联。 That table would have
user_id
and email_id
columns.该表将具有
user_id
和email_id
列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.