Rails 6:我可以创建一个关联的记录委托给当一个新的记录被创建,但不保存?



我有一个与Mobile相关联的CustomerProfile模型,用于处理手机号码验证,短信通知等…

在创建客户配置文件时,我想设置用户的手机号码,就好像该列存在于配置文件表本身一样。为此,我使用了delegate。但是,直到保存新配置文件后才会创建相关的移动记录。

class CustomerProfile < ApplicationRecord
belongs_to :user, optional: true
has_one :mobile, autosave: true, dependent: :destroy
delegate :number, to: :mobile, prefix: :mobile
delegate :number=, to: :mobile, prefix: :mobile
after_create -> { create_mobile }
...
end

所以,我不能创建一个新的客户资料和设置一个手机号码。在设置号码之前,我必须先保存记录。

[1] pry(main)> profile = CustomerProfile.new
TRANSACTION (0.1ms)  BEGIN
=> #<CustomerProfile:0x00007fb371201300 id: nil, first_name: nil, last_name: nil, user_id: nil, created_at: nil, updated_at: nil>
[2] pry(main)> profile.mobile_number = "123"
Module::DelegationError: CustomerProfile#mobile_number= delegated to mobile.number=, but mobile is nil: #<CustomerProfile id: nil, first_name: nil, last_name: nil, user_id: nil, created_at: nil, updated_at: nil>

从我从文档中了解到,这个没有回调。

我不认为这是可能的,因为移动记录需要一个id来指向和客户配置文件没有得到一个,直到它被保存。对吗?

是否有一种方法可以在模型第一次创建时创建关联而不需要保存步骤?

您可以在保存之前在Rails中创建关联对象。

为您has_one协会将像这样

customer_profile = CustomerProfile.new
customer_profile.build_mobile

现在你可以在你的表单中使用customer_profile对象来制作输入字段,或者使用customer_profile.save来保存具有has_one关系的customer_profilemobile对象。