使用HABTM关联添加记录

时间:2014-10-29 22:14:46

标签: ruby-on-rails

我还是在轨道上使用红宝石,我真的被封锁了。 我正在尝试将链接的书籍和作者添加到数据库中,它在两个表中添加记录但不在连接中添加记录。这是我的代码:

books_controller.rb

class BooksController < ApplicationController

  def index
   @books= Book.all
  end

  def new
   @book= Book.new
  end

  def create
   @book= Book.new(book_params)
    if @book.save
     redirect_to books_path
    else
     redirect_to root_url
    end

   end


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

book.rb

class Book < ActiveRecord::Base
  has_and_belongs_to_many :authors
  before_destroy { authors.clear }
end

author.rb

class Author < ActiveRecord::Base
   has_and_belongs_to_many :books
end

书籍/ new.html.erb

<h1>Add new book</h1>
 <%= form_for @book do |f| %>
    <%= f.label :title %>
    <%=f.text_field :title %>
      <% for author in Author.all %>
        <%= check_box_tag 'book(author_ids[])',author.id, @book.authors.include?(author) %>
       <%= author.f_name %>
      <% end%>
     <%= f.submit %>
  <%end%>

1 个答案:

答案 0 :(得分:0)

<%= check_box_tag 'book(author_ids[])',author.id, @book.authors.include?(author) %>更改为<%= check_box_tag 'book[author_ids][]',author.id, @book.authors.include?(author) %>