我使用has_many:通过collection_select在多选中通过多对多关系:multiple =>真正。我不明白,为什么“genre_ids”=> [“”,“2”,“3”,“4”]总是有空的第一个元素?
型号:
class Book < ApplicationRecord
has_many :book_genres
has_many :genres, through: :book_genres
end
class Genre < ApplicationRecord
has_many :book_genres
has_many :books, through: :book_genres
end
class BookGenre < ApplicationRecord
belongs_to :book
belongs_to :genre
end
_form.html.erb
<%= form_for @book do |f| %>
...
<%= f.collection_select(:genre_ids, Genre.all, :id, :genre, {include_blank: "Select genre"}, {multiple: true, size: 6}) %>
...
<%= f.submit %>
<% end %>
books_controller.rb
class BooksController < ApplicationController
def new
@book = Book.new
end
def create
render plain: params.inspect
end
end
参数:
<ActionController::Parameters {
"utf8"=>"✓",
"authenticity_token"=>"8WRSXJHwMyHM....",
"book"=>{"title"=>"",
"genre_ids"=>["", "2", "3", "4"],
"desc"=>"",
"published_at"=>"1982"},
"commit"=>"Create Book",
"controller"=>"books",
"action"=>"create"} permitted: false>
答案 0 :(得分:0)
可能是因为“选择类型”也被选中,因为它是一个多选下拉列表。在将数据发送到服务器之前删除它,或者避免使用“include_blank”选项。