Rails - 表格 HABTM

Rails - Form HABTM

我是 Rails 的新手,但我被卡住了。我想创建一个表单,将数据添加到两个表(书籍和 books_authors)。我的观点如下:

<%= 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>

我在控制器 books_controller.rb 中的创建方法看起来像:

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

和我的架构:

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

我需要 :authors 的参数,但我不知道如何将它嵌套在表单中

我在你的 _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 %>

在你的控制器中,

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

控制器的新代码

定义一个私有方法并把

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

并在

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