0

I have a setup where an author has many sources (and visa versa) through authorships.

I am working on the source form and would like to have a selection dropdown where a user can select multiple authors to be associated with a given source.

My author model looks like this:

class Author < ApplicationRecord

  belongs_to :user
  has_many :authorships
  has_many :sources, through: :authorships

  def last_first
    "#{last_name}, #{first_name}"
  end

  ...
end

My source model:

class Source < ApplicationRecord

  belongs_to :user
  has_many :authorships
  has_many :authors, through: :authorships

  ...

end

And my authorship model:

class Authorship < ApplicationRecord
  belongs_to :source
  belongs_to :author
end

I tried this at first:

    <%= f.collection_select(:author_ids, Author.all, :id, :last_first, multiple: true) %>

But I got this strange error: Could not find the source association(s) "author" or :authors in model Authorship. Try 'has_many :authors, :through => :authorships, :source => <name>'. Is it one of ?

I consulted many SO posts like this, this, and this, but to no avail.

Can anyone help me figure out what I'm doing wrong? The collection_select documentation is not much help.

Liz
  • 1,369
  • 2
  • 26
  • 61

1 Answers1

0

I ended up solving this with a collection_check_boxes like this:

    <%= f.collection_check_boxes :author_ids, Author.all, :id, :last_first do |b| %>
      <div class="field form-check" style="display: block">
        <%= b.check_box class: "form-check-input" %>
        <%= b.label class: "form-check-label" %>
      </div>
    <% end %>

Not a dropdown, but it's functional and saves!

Liz
  • 1,369
  • 2
  • 26
  • 61