我有一个带有用户模型和 Instructor_Profile 模型的简单应用程序。这两个模型之间的关联是一对一的。我无法让我的视图 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>