【问题标题】:Rails namespaced has_many through missing columnRails 命名空间 has_many 通过缺少的列
【发布时间】:2018-12-03 10:16:32
【问题描述】:

在我的 rails 项目中,我有一个命名空间 has_many through 关系 Scheme

models/school/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

models/school/contact/email.rb

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

models/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

我们将不胜感激任何类型的帮助

【问题讨论】:

  • 我感觉问题出在foreign_key 的名称上。您可以为School::Contact::Email 表的belongs_to 条目设置foreign_key: &lt;the correct value&gt; 吗?

标签: ruby-on-rails model namespaces relationship has-many-through


【解决方案1】:

您对此非常接近 - 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

希望对您有所帮助 - 如果您有任何问题,请告诉我您的进展情况并大声疾呼。

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 2012-12-15
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多