Two different relations between same two models

谁都会走 提交于 2019-12-13 05:52:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!