0
0

More than 3 years have passed since last update.

[Rails]フォロー機能導入中にActiveModel::UnknownAttributeErrorというエラー発生

Posted at

はじめに

本記事では、フォロー機能時に発生した
ActiveModel::UnknownAttributeErrorというエラーの解決した方法を記述します。
仲間に助けてもらいながら実装できたため、個人でもアウトプットして身につけたいと思い、記事にしました。

エラー画面

フォロー機能導入できない.png

attribute=属性という意味。(Google先生)

Relationshipにuser_idという属性は知らん。と怒られました。

フォロー機能のsequel pro.png

確かに、user_idはありません。

しかし、binding.pryでparams[:user_id]の値取れてるじゃないですか...。
と言い訳してみたはいいものの、まあカラムにないわけですからなんとかします。

フォロー機能 binding.pry.png

コード

実際のコードがこれです。

relationships_controller.rb
class RelationshipsController < ApplicationController
  before_action :authenticate_user!
  def create
    following = current_user.relationships.build(follower_id: params[:user_id])
    following.save
    redirect_to request.referrer || root_path
  end

  def destroy
    following = current_user.relationships.find_by(follower_id: params[:user_id])
    following.destroy
    redirect_to request.referrer || root_path
  end
end

following = current_user.relationships.build(follower_id: params[:user_id])`

エラーの内容的にここだよね。と思ったので、もうピンポイントで突き止めていきます。

結論

relationships_controller.rb
class RelationshipsController < ApplicationController
  before_action :authenticate_user!
  def create
    following = Relationship.create(follower_id: params[:user_id], following_id: current_user.id)
    redirect_to request.referrer || root_path
  end

  def destroy
    following = Relationship.find_by(follower_id: params[:user_id], following_id: current_user.id)
    following.destroy
    redirect_to request.referrer || root_path
  end
end
following = Relationship.create(follower_id: params[:user_id], following_id: current_user.id)

Relationshipモデルにcreateメソッドつけて、
カラムであるfollower_idfollowing_idをセッターにして、
それぞれ値を入れ込めば完了。

敗因

Relationship.create(follower_id: params[:user_id], following_id: current_user.id)の形で値を入れることを理解できていなかった。

②なんとかして、変数を作って入れることしか考えていなかった。

別解として、
カラムをfollowinguser_idに変えてしまう手もあったようです。

終わりに

完全に仲間に助けてもらい、解決しました。
同じスタートを切ったはずなのに差ができていたことに愕然としたものの、
みんなでディスカッションしながらコードを眺めるのも、楽しいなと感じました。

Railsでフォロー機能を作る方法
【Ruby on Rails】フォロー機能を作ろう(PART2)How to set up a Follower Following system in Ruby on Rails
2つ目はYouTubeですが、
この方の動画はかなり参考になるかと思います。

今日は週末ですが、
明日も頑張ります!!

0
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
0
0