I have a question about two-way has_many data model. I have two models: Book and Author.
Book can have many authors and Author can have many books
I've created form at 'new' action of each entity's controller to create entity object and I want to make so each entity creation form could get a list of the other entity objects with checkboxes, so user could easily select, for example, authors for new book from existing authors and conversely. How do I make so?
Here's the code of two models:
class Book < ActiveRecord::Base
has_many :relationships
has_many :authors, through: :relationships
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
class Author < ActiveRecord::Base
has_many :relationships
has_many :books, through: :relationships
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
And the code of forms:
<%= form_for(@book) do |f| %>
<%= render 'shared/error_messages', object: @book %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.submit "Create book", class: "btn btn-large btn-primary" %>
<% end %>
<%= form_for(@author) do |f| %>
<%= render 'shared/error_messages', object: @author %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.submit "Create author", class: "btn btn-large btn-primary" %>
<% end %>