Nested Polymorphic Association Form

Working on an internal application and I have a Polymorphic association called Roles…

What I am trying to do is associate a user to different models with a role associated…

I have it “partially” working, however when I do an update it fails as one of the records in the params exists already and I don’t allow duplicates…

For an example, I have is a User Model, a LEA Model, a RoleType Model, and a Role Model that is polymorphic…

Here is my Role model:

class CreateRoles < ActiveRecord::Migration[6.0]
  def change
    create_table :roles do |t|
      t.references :user
      t.references :role_type
      t.references :roleable, polymorphic: true, null: false
      t.index [:user_id, :roleable_type, :roleable_id], unique: true
      t.timestamps
    end
  end
end

So what I am doing in the User Controller is this on an Edit (straight build on a new)

  def edit
    n = RoleType.find_by_name('None')
    @leas.where("leas.id NOT IN (?)", @user.roles.pluck('roles.roleable_id')).each do |lea|
      @user.roles.build(roleable_id: lea.id, role_type_id: n.id, roleable_type: 'Lea')
    end
  end

And the role part in my form is like this:

            <%= f.fields_for :roles do |e| %>
                <li>
                  <%= e.hidden_field :roleable_type, value: 'Lea' %>
                  <%= e.collection_select :roleable_id, @leas.order(:name), :id, :name, class: 'form-control' %>
                  <%= e.collection_select :role_type_id, RoleType.order(:name), :id, :name, class: 'form-control' %>
                </li>
            <% end %>

I know this will be confusing so please ask questions… I am not sure what to explain for your assistance…

What I would “like” to do is include all of the target records in the selection and default to None on the role if not changed…

Is there a better way to do this?

John

Duh!

Figured it out…

Did not have :id in the safe params so it always tried to create…