简体   繁体   中英

has_one :through through a join model

I want to build something so that a person can have many email addresses and an email address has only one person, but because I also have another model called Company that also can have many email addresses, and I don't want to have columns company_id and person_id in the Emails table, so I thought I can do ...

person.rb

has_many :person_emails has_many :emails, :through => :person_emails

person_emails.rb

belongs_to :person belongs_to :email

email.rb

has_one :person_email has_one :person, :through => :person_email

What's happening now is that...

p = Person.first #=> "Nik" p.emails #=> shows all emails Nik has p.person_emails #=> shows all person_email joint table records for Nik

e = Email.first #=> one of Nik's email addresses e.person_email #=> shows this email's one and only one person_email joint table record e.person # fails saying that unknown column "people.email_id" in where-clause

I'd like... e.person #=> "Nik"

Does anyone have an idea what the problem might be?

Thank You

Your situation suggests using polymorphic associations, which are much cleaner than has_many :through associations. For example:

class Person
  has_many :emails, :as => :emailable
end

class Company
  has_many :emails, :as => :emailable
end

class Email
  belongs_to :emailable, :polymorphic => true
end

You can get rid of your PersonEmails class entirely. In the database, your emails table will look something like this:

create_table :emails do |t|
  t.string :address
  t.string :emailable_type
  t.integer :emailable_id
end

The emailable_type column stores the name of the associated model, in your case "Person" or "Company" , and the emailable_id stores the id of the associated object. For more information see the Rails API documentation under "Polymorphic Associations".

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