我的Consultation
模型有post_consultant
和consultant
。 post_consultant
和consultant
都是对Employee
模型的引用。所以你可以说:
模型
Class Consultation < ActiveRecord::Base
has_one :employee # for consultant
has_one :employee # for post_consultant
end
移植
create_table "consultations", force: :cascade do |t|
t.boolean "showed_up"
t.boolean "signed_up"
t.integer "client_id"
t.integer "consultant_id"
t.integer "post_consultant_id"
end
我该怎么写呢?
正确的型号:
class Consultation < ActiveRecord::Base
belongs_to :consultant, class_name: "Employee", foreign_key: "consultant_id"
belongs_to :post_consultant, class_name: "Employee", foreign_key: "post_consultant_id"
end
答案 0 :(得分:3)
Class Consultation < ActiveRecord::Base
belongs_to :consultant, :class_name => "Employee", :foreign_key=> "consultant_id", dependent: :destroy
belongs_to :post_consultant, :class_name=>"Employee", :foreign_key=> "post_consultant_id", dependent: :destroy
end
答案 1 :(得分:0)
您可以定义涉及同一模型的多个关系。
Class Consultation < ActiveRecord::Base
has_one :consultant, class_name: 'Employee', foreign_key: :consultant_id
has_one :post_consultant, class_name: 'Employee', foreign_key: :post_consultant_id
end
注意:使用上面的语法提及您为每个关联使用的任何外键。