railsをはじめて3ヵ月の経験ですが、自分のブログを作りたいと思っています。
railsでブログの投稿にカテゴリーを多対多の関係で作ろうとしています。
以下モデルです。
ruby
1#post.rb 2 3class Post < ApplicationRecord 4 has_many :comments ,dependent: :destroy 5 has_many :post_categories, dependent: :destroy 6 has_many :categories, through: :post_categories, source: :category, dependent: :destroy 7 accepts_nested_attributes_for :post_categories, allow_destroy: true 8 9 validates :title, presence: true, length:{ minimum: 5, maximum: 255 } 10 validates :text, presence: true 11end 12------------------------------------------------------------------------------------------------------------------ 13#post_category.rb 14 15class PostCategory < ApplicationRecord 16 belongs_to :post 17 belongs_to :category 18end 19------------------------------------------------------------------------------------------------------------------ 20#category.rb 21 22class Category < ApplicationRecord 23 has_many :post_categories, dependent: :destroy 24 has_many :posts, through: :post_category, source: :post, dependent: :destroy 25 26 validates :name, uniqueness: true 27 28end
以下コントローラです。
ruby
1#posts_controller.rb 2 3class PostsController < ApplicationController 4 5 def new 6 @post = Post.new 7 @post.post_categories.build 8 end 9 10 def create 11 @post = Post.new(post_params) 12 end 13 14 private 15 def post_params 16 params.require(:post).permit(:title, :text, post_categories_attributes: [:id, :category_id]) 17 end 18end
html
1#posts/new.thml.erb 2 3<%= form_for @post do |f| %> 4 <%= render "layouts/error_messages", object: @post %> 5 <div class="form-group"> 6 <%= f.label :title ,"タイトル"%> 7 <%= f.text_field :title, class: "form-control"%> 8 </div> 9 10 <div class="form-group"> 11 <%= f.label :text, "内容"%> 12 <%= f.text_area :text, class: "form-control ", rows: 20 %> 13 </div> 14 15 <%= f.fields_for :post_categories do |i| %> 16 <div class="form-group"> 17 <%= i.label :caregory_id, "カテゴリー" %> 18 <%= i.collection_check_boxes :category_id, Category.all, :id, :name, class: "form-control" %> 19 </div> 20 <% end %> 21 22 <%= f.submit "投稿" ,class: "btn btn-success"%> 23<% end %> 24 25 26 27```### 前提・実現したいこと 28accepts_nested_attributes_forを使ってブログを投稿した時に中間テーブル `post_categories` 29を同時に保存して、ブログにカテゴリーを関連付けしたいと考えております。 30 31tableカラム 32posts: id, title, text, created_at, updated_at 33post_categories: id, post_id, category_id, created_at, updated_at 34categories: id, name, created_at, updated_at 35です。 36 37 38### 発生している問題・エラーメッセージ 39 40エラーメッセージは出ておりませんが中間テーブルが保存されません。 41ディベロッパーツールでパラメータを見ると
post[title]: ffffffefsfga
post[text]: dfghtyejhgfdfdgsfvccbfdhgfdscvxz
post[post_categories_attributes][0][category_id][]:
post[post_categories_attributes][0][category_id][]: 1
post[post_categories_attributes][0][category_id][]: 2
commit: 投稿
となっています。 titleとtextは適当です。 色々と調べましたがうまくいかず、困っています。 改善するアイデアをご存知であれば教えていただけないでしょうか。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/31 15:58