I've created an Address model with a polymorphic association, I am trying to save to it though nested attributes of a client model but I am getting Address addressable must exist in the @client.errors.
Models:
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
Controller:
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
You should add the inverse_of key on your belongs_to relation, e.g. on your Address class:
class Address < ApplicationRecord
belongs_to :addressable, polymorphic: true, inverse_of: :addressable
end
This will save the nested address correctly as Rails will now correctly know what to assign in the addressable.
Don't use the optional key unless the addressable is truly optional.
belongs_to :xx, polymorphic: true, optional: true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With