簡體   English   中英

Rails命名空間has_many通過缺少列

[英]Rails namespaced has_many through missing column

在我的rails項目中,我有一個名稱空間的has_many通過關系Scheme

車型/學校/ contact.rb

class School::Contact < ApplicationRecord

  belongs_to :school, class_name: '::School'

  has_many :school_contact_emails, class_name: 'School::Contact::Email'
  has_many :emails, through: :school_contact_emails, class_name: '::Email'

end

車型/學校/聯系人/ email.rb

class School::Contact::Email < ApplicationRecord
  belongs_to :school_contact, class_name: 'School::Contact'
  belongs_to :email, class_name: '::Email'
end

車型/ email.rb

class Email < ApplicationRecord
  has_many :school_contact_emails, class_name: 'School::Contact::Email'
  has_many :school_contacts, through: :school_contact_emails, class_name: 'School::Contact'
end

如果我打開rails控制台

s = School::Contact.first
=> #<School::Contact id: 1, name: "Headmaster Name", surname: "Headmaster Surname", school_contact_role_id: 1, school_id: 2285, created_at: "2018-06-24 17:47:21", updated_at: "2018-06-24 17:47:21", creator_id: 1, updater_id: 1>

如果我查找電子郵件

s.emails
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column school_contact_emails.contact_id does not exist)

它說school_contact_emails.contact_id不存在,但表列應為“school_contact_id”

這是School :: Contact :: Email表的遷移

class CreateSchoolContactEmails < ActiveRecord::Migration[5.1]
  def change
    create_table :school_contact_emails do |t|
      t.references :school_contact, foreign_key: true
      t.references :email, foreign_key: true

      t.timestamps
      t.userstamps
    end
  end
end

任何類型的幫助將非常感激

你非常接近這一點--Rails實際上希望外鍵反映關聯對象的類+ _id ,在本例中為contact_id ,而不是使用關聯本身的名稱(在本例中為school_contact )。

這為您提供了兩個選項:您可以重命名數據庫中的列,也可以將foreign_key選項添加到關聯中。

例如:

class School::Contact::Email < ApplicationRecord
  belongs_to :school_contact, class_name: 'School::Contact', foreign_key: 'school_contact_id'
  belongs_to :email, class_name: '::Email'
end

希望有所幫助 - 如果您有任何疑問,請告訴我您的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM