【问题标题】:Rails Association: 2 occurrences of same modelRails 协会:同一模型出现 2 次
【发布时间】:2017-11-03 12:37:02
【问题描述】:

我有一个Consultation 模型,它有一个post_consultant 和一个consultantpost_consultantconsultant 都是对 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

【问题讨论】:

  • post_consultant和consultant是模特吗?
  • post_consultant 和 advisor 哪个外键?
  • 只有员工是模特

标签: ruby-on-rails activerecord associations


【解决方案1】:
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

【讨论】:

  • 这很奇怪,当我尝试时:c = Consultation.newe = Employee.first。然后尝试c.consultant = e 我看到以下错误:ActiveModel::MissingAttributeError: can't write unknown attribute 'consultant_id'
  • 请确认您在schema的consultations表中是否有字段consult_id和post_consultant_id列
  • 咨询表里都有
  • @Jeremy Thomas,那么我们需要改变关联,它应该是belongs_to
  • 呃呃呃呃!谢谢
【解决方案2】:

您可以定义引用同一模型的多个关系。

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

注意:使用上述语法提及您为每个关联使用的任何外键。

【讨论】:

  • 请参阅上面回复的评论
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多