1

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 %>
  • what have you tried so far? This looks like the scaffolding code? What have you tried? Where did you stumble? – Aravind May 24 '14 at 22:10
  • 1
    You're looking for accepts_nested_attributes_for on a has_many through relationship. This should get you going: http://stackoverflow.com/questions/2182428/rails-nested-form-with-has-many-through-how-to-edit-attributes-of-join-model – James Mason May 25 '14 at 01:21

0 Answers0