Rails中如何从embedded_in关联反向调用属性?Mongoid问题
解决Mongoid嵌入式模型获取父模型属性的问题
问题原因
你之前尝试用field :account_id, type: String, default: -> { person.account_id }报错,是因为嵌入式文档初始化时还未与父模型建立关联,此时person对象为nil,调用person.account_id自然触发NoMethodError。
解决方案
根据是否需要持久化该字段,提供两种实现方式:
方式一:持久化字段(同步父模型值)
如果需要将account_id存储到PersonInfo文档中,可通过回调在关联建立后赋值:
class PersonInfo include Mongoid::Document field :first_name, type: String field :last_name, type: String field :account_id, type: String # 新增字段 embedded_in :person validates :first_name, :last_name, presence: true before_validation :sync_account_id_from_person private def sync_account_id_from_person # 安全调用,避免person为nil时出错 self.account_id = person&.account_id end end
- 每次
PersonInfo验证或保存时,会自动从关联的Person同步account_id - 若
Person的account_id后续修改,保存Person时会触发PersonInfo的回调,自动更新该字段
方式二:虚拟属性(实时获取父模型值)
如果不需要持久化该字段,仅需在代码中访问,可定义虚拟属性,避免数据冗余:
class PersonInfo include Mongoid::Document field :first_name, type: String field :last_name, type: String embedded_in :person validates :first_name, :last_name, presence: true # 虚拟属性,实时从父模型获取值 def account_id person&.account_id end end
- 每次调用
person.person_info.account_id时,都会实时从关联的Person读取account_id - 无需存储字段,节省数据库空间,且始终与父模型值保持一致
内容的提问来源于stack exchange,提问作者Peter T. Walker
相关产品推荐
相关产品推荐

