LoginSignup
4
2

More than 3 years have passed since last update.

ストロングパラメーターに外部キーを渡す方法

Posted at

概要

ポートフォリオに投稿機能を実装中、ストロングパラメーターを用いて値を渡そうとしたのですが
何度やっても投稿が保存されませんでした。

  def create
    @post = Post.new(post_params)
    binding.pry
    if @post.save
      flash[:success] = "投稿しました"
      redirect_to posts_path
    else
      render action: :new
    end
  end

binding.pryを差し込んでデバッグしたみたのですが結果は

permitted: true

じゃあなんで投稿できない。。

調べたところ単純な記述ミスでした。

軽くハマってしまったので自分の備忘録も兼ねての投稿です。

開発環境

  • Rails 6.0.3.4
  • ruby 2.6.3

実装方法

元々のコード

def post_params
  params.require(:post).permit(:user_id, :title, :content, :price, :img)
end

正しいコード

def post_params
  params.require(:post).permit(:title, :content, :price, :img).merge(user_id: current_user.id)
end


外部キーのuser_idを渡す時にmergeメソッドを使ったら投稿できるようになりました!!

4
2
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
4
2