【发布时间】:2020-12-06 02:34:10
【问题描述】:
我有一个客户的嵌套关联。设置是这样的:
- 一位客户有一个地址
- 地址具有物理地址
- 地址有一个 postal_addrsss
地址模型
belongs_to :customer, optional: true # Yes, optional
has_one :physical_address, dependent: :destroy
has_one :postal_address, dependent: :destroy
accepts_nested_attributes_for :physical_address
accepts_nested_attributes_for :postal_address
邮政地址模型
# same for physical_address.rb
belongs_to :address
客户控制员:
def create
@customer = current_user.customers.build(customer_params)
if @customer.save
return puts "customer saves"
end
puts @customer.errors.messages
#redirect_to new_customer_path
render :new
end
private
def customer_params
params.require(:customer).permit(
address_attributes: address_params
)
end
def address_params
return ([
postal_address_attributes: shared_address_params,
#physical_address_attributes: shared_address_params
])
end
def shared_address_params
params.fetch(:customer).fetch("address").fetch("postal_address").permit(
:street, etc...
)
end
客户模型:
has_one :address, dependent: :destroy
accepts_nested_attributes_for :address
客户创建成功,但地址未创建。例如下面的表格:
<form>
<input name="customer[address][postal_address][street]" value="Foo Street" />
</form>
记录“参数”,我看到了所有值,但地址没有创建。我相信错误在于shared_address_params。有什么想法吗?
【问题讨论】:
-
客户模型是否接受地址的嵌套属性?
-
同意@dbugger 另外,Sylar 可以更新你有问题的参数
-
@dbugger,是的。我已经更新了问题。
-
@AnandBait 你是什么意思?
-
@Sylar 我的意思是你能把你在终端上看到的参数贴出来,这样我们就可以检查参数和传递的嵌套属性。
标签: ruby-on-rails activerecord associations ruby-on-rails-6 model-associations