0

I'm working in Rails 5.

In my database, I have a table called publications and a table called authors which have a HABTM relationship.

I want to build a form that lets users insert more publications into my db, and part of this is associating existing (or new) authors to each new publication.

What's the best way to do this?

Here's my relevant code:

publication.rb

class Publication < ApplicationRecord

  self.table_name = "publications"
  has_and_belongs_to_many :authors

end

author.rb

class Author < ApplicationRecord

  self.table_name = "authors"
  has_and_belongs_to_many :publications

end

_form.html.erb

<h3>Publication name:</h3>
<p><%= f.text_field(:name) %></p>

<h3>Authors</h3>
<p><%= ??? %></p>

<h3>Citation:</h3>
<p><%= f.text_field(:citation) %></p>
league
  • 245
  • 1
  • 9
  • `has_and_belongs_to_many` is sometimes pretty clunky compared to a `has_many` and `has_many through:` relationship pair. Something worth considering when implementing a feature like this. With the `through:` method you get to pick if you want to deal with the relationship records directly, which is often handy when selecting via check-boxes, and you can easily add metadata to the relationship itself, like roles or other attributes. – tadman Jul 25 '17 at 21:57
  • You should be able to call `publication.authors.each` if your data is populated correctly though. – tadman Jul 25 '17 at 21:58
  • you can use, accepts_nested_atributes_for and https://github.com/nathanvda/cocoon for your dynamic forms – buncis Jul 26 '17 at 08:44

0 Answers0