38
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Validation failed: モデル must existエラー

Posted at

ユーザーがつぶやきを投稿できるTweetみたいなサイトを作成中

今回やりたいこと
formから投稿(post)を送ってDBに保存(ユーザーに紐づいた)してviewに表示させる

苦戦した内容
投稿するもDBに保存されない

調べた内容
bindinng.pryでparamsが送られているかストロングパラメーターがtrueか調べるも問題はなし

@post.save!と記述すると下記のエラーが出たので検索

ActiveRecord::RecordInvalid: Validation failed: Genre must exist

要約するとgenreモデルに値が入ってなくてバリデーションで弾かれていたみたい

解決策
optional: trueを記載

post.rb
class Post < ApplicationRecord
belongs_to :user
belongs_to :genre, optional: true
end

optional: trueとはなにか?

Railsのbelongs_toに指定できるoptional: trueとは?
belongs_toの外部キーのnilを許可するというもの

参考

モデル

post.rb
class Post < ApplicationRecord
belongs_to :user
belongs_to :genre
end
user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  # validates :username, presence: true
  has_many :posts, dependent: :destroy
end
genre.rb
class Genre < ApplicationRecord
has_many :posts
end

コントローラー

posts_controller.rb
class PostsController < ApplicationController

# before_action :authenticated_user!

  def title

  end

  def index
    @post = Post.all
  end

  def new
    @post = Post.new
    # binding.pry
  end

 def show
  @post = Post.limit(6)
 end

def create
  @post = Post.new(posts_params)
  @post.save
  binding.pry
  redirect_to posts_path(@post)

end

def edit
 @post = Post.find(params[:id])
end


def update
  post = Post.find(params[:id])
  post.update(text: posts_params[:text])
 redirect_to action: "index"
end

def destroy
  post = Post.find(params[:id])
  post.destroy
  redirect_to action: "index"
end

  private
    def posts_params
      # binding.pry
    params.require(:post).permit(:text).merge(user_id: current_user.id)
  end

end


end
38
37
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
38
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?