相关模型属性继承

问题描述:

Rails新手在这里。我有相关的定义的模型TeamVenue如下:相关模型属性继承

class Team < ApplicationRecord 
    has_many :home_venues, class_name: "Venue" 
end 

class Venue < ApplicationRecord 
    belongs_to :team, optional: true, foreign_key: :team_id 
end 

两款车型有属性:city:region。当我呼叫team.home_venues.create时,除非另有说明,否则我希望新创建的venue:city:region值默认为创建team:city:region值。

实现此功能的最佳方式是什么?

我会使用before_validation挂钩 - 这种方式,你将确保你将所有的验证在正确的时间运行。在您的Venue型号中:

before_validation :set_default_values 

def set_default_values 
    self.city ||= self.team.try(:city) 
    self.region ||= self.team.try(:region) 
end