やりたい事:記事を登録した際に複数のカテゴリーを紐付けるようにしたい。
modelの関係
Article←CategoriesArticle→Category
●詰まっている所●
Articleフォームでデータ登録したと同時にCategoriesArticle(中間テーブル)へデータ登録される用にしたいが、ストロングパラメーターの所が301でエラーになってしまいます
controllerの部分のcreateの処理かnewの処理が原因かと思うのですが、エラーの切り分けができなかった為どなたかご教授いただければ存じます。
■modelの関係■
Article←CategoriesArticle→Category
Article.model
ruby
1class Article < ActiveRecord::Base 2 belongs_to :category, inverse_of: :articles 3 4 has_many :categories_articles 5 has_many :categories, through: :categories_articles 6 accepts_nested_attributes_for :categories_articles 7end
Category.model
ruby
1class Category < ActiveRecord::Base 2 has_many :articles, inverse_of: :category 3 4 has_many :categories_articles 5 has_many :articles, through: :categories_articles 6end
CategoriesArticle.Model(中間テーブル)
ruby
1class CategoriesArticle < ActiveRecord::Base 2 belongs_to :category 3 belongs_to :article 4end 5
articleController
ruby
1def new 2 @article = Article.new 3 @article.categories_articles.build 4 end 5 6 def create 7 @article = Article.new(article_params) 8 ... 9 end 10 11private 12 def article_params 13 params.require(:article).permit(:title, :categories_articles => [:category_id]) 14 end
article.form
ruby
1- url = @article.new_record? ? dashboards_path : dashboard_path 2 3= simple_form_for(@article, url: url) do |f| 4 = f.input :title, maxlength:'60' 5 = f.fields_for :categories_articles do |fc| 6 = fc.select :category_id, Category.all.map{|o| [o.name, o.id]}
フォームParameters
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Oq4VCC84YaSHkPgFi8++oC8OQq/O+EVkkHNHtvcQiQK2ICtC2IPC7ez3W1O5M+7aUc9ziI0goKypCdYBLpVp9A==", "article"=>{ "title"=>" ","categories_articles_attributes"=>{"0"=>{"category_id"=>"1"}} Completed 302 Found in 121ms (ActiveRecord: 38.5ms)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。