5
0

More than 3 years have passed since last update.

can't write unknown attribute `category_id`を解決した話

Last updated at Posted at 2020-06-08

投稿機能でpost投稿する際にcan't write unknown attributecategory_idが出現した為、記録用に投稿。

仕様

https://qiita.com/cawaz3/items/e755a58177212f2aca6c
テーブル構成等はこちらの記事を参考。
中間テーブルを実装し投稿時にタグidを紐付けた。

症状

投稿画面にて投稿内容記述後に投稿確認画面に遷移する設定にしているが上記のエラーが出てしまいうまく遷移されない様子。

原因

カラム名の相違
post.controller.rbではcategory_idで記述していたのにも関わらずテーブルを確認した際にcategories_idになっていた。

post.controller.rb
def confirm
    @post = Post.new(post_params)
    session[:category_ids] =  @post.category_ids
    return if @post.valid?
    flash.now[:alert] = '入力に不備がありました。'
    render :new
  end

  def back
    @post = Post.new(post_params)
    render :new
  end

  private

  def post_params
    params.require(:post).permit(:post_photo,
                                 :post_photo_cache,
                                 :place_name,
                                 :area,
                                 :street_address,
                                 :time,
                                 :regular_holiday,
                                 :url,
                                 :station,
                                 :shop_name,
                                 category_ids: []).merge(user_id: current_user.id )
  end
end
select * from post_category_relations;
 id | posts_id | categories_id | created_at | updated_at 
----+----------+---------------+------------+------------
(0 rows)

改善方法

モデルの記述を変更しrails db:migrate:reset

class CreatePostCategoryRelations < ActiveRecord::Migration[5.2]
  def change
    create_table :post_category_relations do |t|
      t.references :post, foreign_key: true, null: false
      t.references :categories, foreign_key: true, null: false⇦変更前
      t.references :category, foreign_key: true, null: false⇦変更後
      t.timestamps
    end
  end
end
5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0