问题
I have two models: users and emails.
I have separated this tables because we want the user to be able to have many emails in the same user account, and also easily check uniqueness of email values among accounts.
primary_email_id is a FK of a unique email, but also a user has many emails. How do I say that in the rails model?
I was trying
class User < ActiveRecord::Base
# relations
has_many :emails
has_one :primary_email
end
…
class Email < ActiveRecord::Base
# relations
belongs_to :user
end
Is that correct? How does rails know when I say primary_email I'm making reference to the emails table?
By the way, both migrations are:
create_table :users do |t|
t.string :username
t.string :first_name
t.string :last_name
t.binary :password
# t.integer :primary_email
t.timestamps null: false
end
create_table :emails do |t|
# t.integer :user
t.string :email
t.boolean :verified
t.timestamps null: false
end
add_reference :users, :primary_email, references: :emails, index: true, foreign_key: true
add_reference :emails, :user, index: true, foreign_key: true
来源:https://stackoverflow.com/questions/31889580/two-different-relations-between-same-two-models