我有以下has_many:通过情况:
class User < ApplicationRecord
has_many :term_enrollments, foreign_key: 'builder_id'
has_many :terms, through: :term_enrollments
end
class TermEnrollment < ApplicationRecord
belongs_to :term
belongs_to :builder, class_name: 'User'
end
class Term < ApplicationRecord
has_many :builder_term_enrollments, class_name: 'TermEnrollment', foreign_key: 'builder_id'
has_many :builders, through: :builder_term_enrollments, source: :builder
end
以下成功创建了term_enrollment:
u = User.first
t = Term.first
u.terms << t
然后我可以成功运行u.terms
。问题是如果我运行t.builders
,我得到一个空关联:
=> #<ActiveRecord::Associations::CollectionProxy []>
我很确定我错误地使用source
,但我不确定如何使用 [Table("EMPLOYMENT")]
public class Employment
{
private DateTime _StartDate;
[Column("STARTDATE")]
public DateTime StartDate
{
get
{
return _StartDate;
}
set
{
_StartDate = value;
StartMonth = value.ToString("MMMM") ?? null;
}
}
[Column("STARTMONTH")]
public string StartMonth { get; set; }
}
。我该如何解决这个问题?
答案 0 :(得分:0)
您可以尝试将:builder_term_enrollments
中的外键设置为'term_id'
或:term_id
吗?
这将使ActiveRecord能够找到具有相应term_id的任何行。
答案 1 :(得分:0)
重写术语模型修复它:
class Term < ApplicationRecord
has_many :builder_term_enrollments, class_name: 'TermEnrollment', source: :builder
has_many :builders, through: :builder_term_enrollments
end