Rails 关联:同一模型出现 2 次
Rails Association: 2 occurrences of same model
我有一个 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
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
您可以定义引用同一模型的多个关系。
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
注意:使用上述语法提及您为每个关联使用的外键。
我有一个 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
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
您可以定义引用同一模型的多个关系。
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
注意:使用上述语法提及您为每个关联使用的外键。