Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested attributes with polymorphic association in Rails 5

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
like image 520
Sir Lancelot of Camelot Avatar asked May 07 '16 20:05

Sir Lancelot of Camelot


2 Answers

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.

like image 58
mtrolle Avatar answered Oct 11 '22 00:10

mtrolle


 belongs_to :xx, polymorphic: true, optional: true
like image 20
alvin2ye Avatar answered Oct 10 '22 23:10

alvin2ye