Search code examples
ruby-on-railsrelational-databaserelationshippolymorphic-associations

Polymorphic relationship


my problem is in generating a record of a partner within a company with a polymorphic migration. The partner comes from my collection of users.

This is my form

<%= form_with(model: [@company, @partner], remote: true) do |f| %>
            <div class="form-group">
                <%= f.label 'Selecciona un socio' %>
                <%= f.collection_select(:partnershipable_id, User.all, :id, :name, {:prompt => 'Selecciona'}, {class: 'form-control'}) %>
            </div>
<% end %>

my models are

app/models/partner

class Partner < ApplicationRecord
  belongs_to :company
  belongs_to :partnershipable, polymorphic: true
end

app/models/user

class User < ApplicationRecord
    has_many   :partners, as: :partnershipable
end

app/models/company

class Company < ApplicationRecord
    has_many    :partners, as: :partnershipable
end

how the form should look to save the user correctly as a partner.


Solution

  • If you want to select a polymophic association you need to provide a type as well.

    <%= form_with(model: [@company, @partner], remote: true) do |f| %>
      <div class="form-group">
        <%= f.label 'Selecciona un socio' %>
        <%= f.collection_select(:partnershipable_id, User.all, :id, :name, {:prompt => 'Selecciona'}, {class: 'form-control'}) %>
        <%= f.hidden_input(:partnershipable_type, 'User') %>
      </div>
    <% end %>
    

    Since the type appears to be fixed I you could probally set the value in the controller on the recieving end as well.