0

User モデルと Instructor_Profile モデルを備えたシンプルなアプリがあります。これら 2 つのモデル間の関連付けは 1 対 1 です。ビュー show.html.erb をレンダリングできません。Instructor_Profile モデルから単一の属性を表示しようとしているだけで、次のエラーが発生します。

Instructor_profiles の NoMethodError#show undefined method `name' for nil:NilClass

どんな助けでも大歓迎です!

Models:

class User
has_one :instructor_profile

class InstructorProfile
belongs_to :user


UsersController:

def new
  @user = User.new
end


def create
  @user = User.new(params[:user])
  if @user.save
    UserMailer.welcome_email(@user).deliver
    render 'static_pages/congratulations'
  else
    render 'new'
  end
end



InstructorProfilesController:

def new
  @instructor_profile = current_user.build_instructor_profile
end


def create
  @instructor_profile = current_user.build_instructor_profile(params[:instructor_profile])
  if @instructor_profile.save
    flash[:success] = "Profile created!"
    redirect_to root_path
  else
  ....
  end
end


def show
  @user = User.find(params[:id])
  @instructor_profile = @user.instructor_profile
end



Views/instructor_profiles/show.html.erb:

<p>Display Name: <%= @user.instructor_profile.name %></p> 
4

1 に答える 1

0

@user.instructor_profileであるから起こるnil。つまり、に対応するinstructor_profileがないということです@user。作成中かどうかはcreate内のメソッドで確認してください。コードは次のようになります。UserControllerinstructor_profile

@user.instructor_profile = InstructorProfile.new(name: "my_name")
@user.instructor_profile.save

編集:

has_one 関連付けは、すべてのユーザーがインストラクター プロファイルを持っている必要があるという意味ではありません。したがって、 を呼び出す前に、持っているかどうか@user.instructor_profile.nameを確認し@userinstructor_profileください。ビューでは、1 つの条件を追加することで、このエラーを簡単に解決できます。

<p>Display Name: <%= @user.instructor_profile ? @user.instructor_profile.name : "no instructor_profile present" %></p>.

もう 1 つinstructor_profiles_controller/show、 のコードを次のように変更します。

@instructor_profile = InstructorProfile.find(params[:id])
 @user = @instructor_profile.user
于 2013-04-24T06:30:38.570 に答える