0
私はcollection_select:multiple => trueを使って複数選択でhas_many:many-to-manyリレーションを使用します。私は、なぜ "genre_ids" => [""、 "2"、 "3"、 "4"]が常に最初の要素が空であるのか理解できませんか?複数のセットがtrueのCollection_select。なぜparams [:book] [:genre_ids] = ["" 1 "、" 2 "]
モデル:
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>
%> f.collection_select(:genre_ids、genre.all、:id、:genre、{}、{multiple:true、size:6})%>何も変更されていません – MDiggit