mike927
mike927

Reputation: 774

Rails - Form HABTM

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

Upvotes: 0

Views: 526

Answers (1)

Emu
Emu

Reputation: 5905

I n your _form

<% @authors.each do |author| %>
  <%= check_box_tag "author_ids[]", author.id %>
  <%= author.name %> // I assume that your author has a name which can be used as a label
<% end %>

in your controller,

def create
  // you will get the authors in params[:author_ids]
  @book = Book.new(params.require(:book).permit(:title, :author_ids => [])) // its a dirty code
  // skip other codes
end

fresh code for controller

define a private method and put

def book_params
 params.require(:book).permit(:title, :author_ids => [])
end

and in

def create
  @book = Book.new(book_params)
end

Upvotes: 5

Related Questions