在我的Rails项目中,我有一个通过关系命名的has_many Scheme
models / school / contact.rb
[System.Serializable]
public class Edge
{
public Node A;
public Node B;
public Edge (Node A, Node B)
{
this.A = A;
this.B = B;
}
}
models / school / contact / email.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 / email.rb
class School::Contact::Email < ApplicationRecord
belongs_to :school_contact, class_name: 'School::Contact'
belongs_to :email, class_name: '::Email'
end
如果我打开Rails控制台
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
如果我要查找电子邮件
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>
它说school_contact_emails.contact_id不存在,但是表列应该是“ school_contact_id”
这是School :: Contact :: Email表的迁移
s.emails
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column school_contact_emails.contact_id does not exist)
任何类型的帮助将不胜感激
答案 0 :(得分: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
希望有帮助-如果您有任何疑问,请告诉我您如何上车和喊叫。