I am new to Rails but I am stuck. I would like to create a form that will add data to two tables (books and books_authors). My view looks like:
<%= form_for :book, url: book_path do |f| %>
<p>
<%= f.label :title %> :<br/>
<%= f.text_field :title %><br/>
<ul>
<% @authors.each do |x| %>
<li> <%= f.check_box {...} %> <%= x.name + " " + x.surname%></li>
<% end %>
</ul>
</p>
<p><%= f.submit %></p>
and my create method in controller books_controller.rb looks like:
def create
@book = Book.new(params.require(:book).permit(:title))
@book.save
params[:authors].each do |author_id|
book.authors << Author.find(author_id)
end
redirect_to root_path
end
and my schema:
ActiveRecord::Schema.define(version: 20150709110928) do
create_table "author_books", id: false, force: :cascade do |t|
t.integer "author_id"
t.integer "book_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "author_books", ["author_id"], name:
"index_author_books_on_author_id"
add_index "author_books", ["book_id"],
name:"index_author_books_on_book_id"
create_table "authors", force: :cascade do |t|
t.string "name"
t.string "surname"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "books", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I need params for :authors but I dont know how to nest it inside the form