お世話になってます。開発初心者です。よろしくお願いします。
###前提・実現したいこと
Railsでリストボックス(複数選択)を使って親子テーブルを同時に更新したい
親:投稿テーブル(Post)
子:カテゴリテーブル(Category)
これらの他に、カテゴリ一覧を持っているCategory_Listテーブルがあります。
カテゴリはリストボックスで複数選択可能
Post 1:N Category
画面遷移は
登録画面 - 確認画面 - 完了画面
###発生している問題・エラーメッセージ
登録画面で選択したカテゴリを確認画面で拾えない。
DBに格納できない。(やりかたがわからない)
###ソースコード
ruby
1#Postモデル 2#id, title 3 has_many :category 4 accepts_nested_attributes_for :category
ruby
1#Categoryモデル 2#id, post_id, category_id 3 belongs_to :post
ruby
1#コントローラ 2 def new 3 @post = Post.new() 4 end 5 6 def confirm 7 @post = Post.new(post_params) 8 end 9 10 def create 11 @post = Post.new(post_params) 12 @post.save 13 end
ruby
1#ビュー(new) 2 <%= form_for @post, :url => {:action => :confirm} do |f| %> 3 <%= f.text_field :title %> 4 5 <%= f.fields_for "category_attributes[]", Category.new do |c| %> 6 <%= c.select(:category_id ,get_category_list().map{|t| [t.key, t.id]} ,{},{:multiple => true}) %> # <= get_category_list()でカテゴリ一覧を取得しています。 7 <% end %> 8 <% end %>
ruby
1#ビュー(confirm) 2 <%= form_for @post, :url => {:action => :create}} do |f| %> 3 <%= f.text_field :title %> 4 5 <%= f.fields_for "category_attributes[]", Category.new do |c| %> 6 <%= @post.category.category_id %> #<= ここがうまく表示できない(デバッグすると値は配列で入ってる) 7 <% end %> 8 <% end %>
###補足情報(言語/FW/ツール等のバージョンなど)
ruby 2.2.2p95
rails 4.2.3
Mac OS 10.11.2
あなたの回答
tips
プレビュー