Ruby on rails 在一对多关系中,我应该为所有行包含默认值还是只检查nil? class Employee

Ruby on rails 在一对多关系中,我应该为所有行包含默认值还是只检查nil? class Employee,ruby-on-rails,relationship,Ruby On Rails,Relationship,有一个默认办公室,所有员工都在其中,有些员工将在另一个办公室。是否最好将每个人的外键设为空,只包含特殊人员的值,或者创建一个办公室,并将其设为除特殊人员以外的所有人的默认值?我建议您将您的关系更改为以下内容: class Employee < ActiveRecord::Base has_one :office end class Office < ActiveRecord::Base belongs_to :employee end 若要创建默认值,可以在Office模

有一个默认办公室,所有员工都在其中,有些员工将在另一个办公室。是否最好将每个人的外键设为空,只包含特殊人员的值,或者创建一个办公室,并将其设为除特殊人员以外的所有人的默认值?

我建议您将您的关系更改为以下内容:

class Employee < ActiveRecord::Base
  has_one :office
end
class Office < ActiveRecord::Base
  belongs_to :employee
end

若要创建默认值,可以在Office模型上添加一个类方法,以便在新员工未设置任何Office时使用默认Office:

montreal_employees = Office.where(location: 'Montreal').employees
montreal_employees = Office.where(location: 'Montreal').employees
# Office model
def self.default
  self.where(internal_reference: :default).first # this line implies that you have a column internal_reference
  # and that there is a record having it set to 'default'
end

# Employee model
before_create :set_office_to_default, if: ->{ self.office_id.blank? }

def set_office_to_default
  self.office = Office.default
end