我创建了一个Address具有多态关联模型,我想救它,虽然客户端模型嵌套的属性,但我得到Address addressable must exist的@client.errors.
楷模:
class Client < ApplicationRecord
has_one :address, as: :addressable, dependent: :destroy
accepts_nested_attributes_for :address, :allow_destroy => true
end
class Address < ApplicationRecord
belongs_to :addressable, polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)
控制器:
class ClientsController < ApplicationController
def new
@client = Client.new
@client.create_address
end
def create
@client = Client.new(client_params)
if @client.save
...
else
...
end
end
private
def client_params
params.require(:client).permit(:first_name ,:last_name, :company, address_attributes: [:line1, :line2, :line3, :city, :state_province, :postal_code, :country])
end
end
Run Code Online (Sandbox Code Playgroud)
您应该inverse_of在您的belongs_to关系上添加密钥,例如在您的Address班级上:
class Address < ApplicationRecord
belongs_to :addressable, polymorphic: true, inverse_of: :addressable
end
Run Code Online (Sandbox Code Playgroud)
这将正确保存嵌套地址,因为 Rails 现在将正确知道要在addressable.
optional除非确实是可选的,否则不要使用该密钥addressable。
小智 5
belongs_to :xx, polymorphic: true, optional: true
Run Code Online (Sandbox Code Playgroud)
还
optional: true
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,您可以通过分两步中断控制器中的创建来保持强制关系。
def client_params
params.require(:client).permit(:first_name ,:last_name, :company)
end
def address_params
params.require(:client).require( :address_attributes).permit(:line1, :line2, :line3, :city, :state_province, :postal_code, :country )
end
def create
@client = Client.new(client_params)
if @client.save
@client.create_address( address_params )
...
Run Code Online (Sandbox Code Playgroud)
这可能看起来更难看,但它可以让关系更安全。
| 归档时间: |
|
| 查看次数: |
2931 次 |
| 最近记录: |