railsで1対1のアソシエーションをしているのですが、rails s
するとNoMethodErrorが出てしまい前に進めません。
コードは下記の通りになります。
エラーが出るのはedit
アクションの@profile = current_user.profile
で、エラーメッセージはundefined method "profile" for nil:NilClass
になります。
ご教授よろしくお願いします!
↓ProfilesController
class ProfilesController < ApplicationController def new @profile = current_user.build_profile end def create @profile = current_user.build_profile(profile_params) if @profile.save flash[:success] = 'プロフィールを作成しました。' redirect_to @profile else flash.now[:danger] = 'プロフィールを作成できませんでした。' render :new end end def edit @profile = current_user.profile end def update @profile = current_user.profile if @profile.update(profile_params) flash[:success] = 'プロフィールを更新しました。' redirect_to @profile else flash.now[:danger] = 'プロフィールを更新できませんでした。' render :new end end private def profile_params params.require(:profile).permit(:name, :comment) end end
↓Profile.rb
class Profile < ApplicationRecord validates :name, presence: true, length: { maximum: 20 } validates :comment, presence: true, length: { maximum: 300 } belongs_to :user end
↓User.rb
class User < ApplicationRecord # Include default devise modules. Others available are: # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_one :profile, dependent: :destroy end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/06/12 08:39