cocoonで渡される値がupdate時にパラメーターで中身を見てみると普通の配列でなってしまい、コントローラーで制御するのが難しいのでcocoonで渡される値を連想配列にして渡されたいのです。
createで作るときは連想配列になっているのでとても扱いやすかったのですが、update時にはなぜか普通の配列でバラバラで渡されるので制御しにくいのです。createするときするみたいに連想配列で渡されたいです。
create
1"categories_items_attributes"=> 2{"0"=>{"big_category_id"=>"6", "small_category_id"=>["1", "2", "3", "40"]}, 3"1591676570948"=>{"big_category_id"=>"15", "small_category_id"=>["1", "25", "43"]}, 4"1591676576449"=>{"big_category_id"=>"16", "small_category_id"=>["1", "26", "36"]}, 5"1591676581466"=>{"big_category_id"=>"", "small_category_id"=>["19", "20", "36"]}}
update
1"b"=>"12", "s"=>["", "1", "24", "38"], "i"=>"27", "m"=>["", "5", "13", "16"], "g"=>"29", "a"=>["", "16", "24", "25", "35"]
View
1<% for i in 0..@small_array.length-1 do %> 2 <li class="string input optional stringish" id="item_category_input"> 3 <%= f.label :カテゴリー %> 4 <%= f.collection_select(:big_category_id[i], Category.where(genre_div: 0), :id, :name, {selected: @big_category_ids[i].id}) %> 5 </li> 6 <li class="string input optional stringish" id="item_category_input"> 7 <div class="small_category_field"> 8 <%= f.collection_check_boxes(:small_category_id[i], Category.where(genre_div: 1), :id, :name, {checked: @small_array[i].map(&:to_param)}) do |b| %> 9 <%= b.label { b.check_box + b.text} %> 10 <% end %> 11 </div> 12 </li> 13<% end %> 14<div class = "links"> 15 <%= link_to_add_association 'add new', f, :categories_items, :partial => 'categories_items_fields', :force_non_association_create => true %> 16</div>
controller
1def edit 2 @small_category_all = Category.where(genre_div: 1) 3 @small_pluck_ids = @small_category_ids.pluck(:id) 4end 5 6def set_category 7 @category_item = CategoriesItem.where(item_id: @item.id) 8 @big_pluck_ids = @category_item.pluck(:big_category_id) 9 @big_ids = @big_pluck_ids.uniq 10 @big_category_ids = Category.where(id: @big_ids) 11 @small_array = Array.new(@big_ids.length) 12 # 配列は0スタートの為、−1しております。 13 for i in 0..@big_ids.length-1 do 14 @small_ids = @category_item.where(big_category_id: @big_category_ids[i]) 15 @small_pluck_ids = @small_ids.pluck(:small_category_id) 16 @small_category_ids = Category.where(id: @small_pluck_ids) 17 @small_array[i] = @small_category_ids 18 end 19end 20
model
1class Item < ApplicationRecord 2 has_many :categories_items, foreign_key: 'item_id' 3 has_many :categories, through: :categories_items 4 accepts_nested_attributes_for :categories_items 5end 6 7class CategoriesItem < ApplicationRecord 8 belongs_to :item, optional: true 9 belongs_to :category, optional: true 10end 11 12class Category < ApplicationRecord 13 has_many :categories_items 14 has_many :categories, through: :categories_items 15end 16
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/06/10 06:36 編集
2020/06/10 09:10