2013-04-24 85 views
0

我有一个简单的应用程序,用户模型& Instructor_Profile模型。这两种模式之间的关联是一对一的。我无法让我的视图show.html.erb呈现。我只是想显示从Instructor_Profile模型的单一属性,我得到这个错误:Rails - 使用一对一关联的模型显示Action&View?

NoMethodError在Instructor_profiles#显示零 未定义的方法`名”: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> 
+0

您是否尝试过用@ instructor_profile.name? – 2013-04-24 05:31:20

+0

嗨Soni。是的,我也尝试过。同样的结果。 – mattq 2013-04-25 00:52:54

回答

0

它发生是因为@user.instructor_profilenil。 这意味着没有与@user对应的instructor_profile。 请检查UserController中的create方法以确认instructor_profile是否正在创建。代码应该是这样的,

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

编辑:

HAS_ONE协会并不意味着每个用户都必须有一个instructor_profile。因此,在拨打@user.instructor_profile.name之前,请确认@user是否有instructor_profile。在您看来,您可以通过添加一个条件轻松解决此错误。

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

还有一件事,在instructor_profiles_controller/show,代码变成

@instructor_profile = InstructorProfile.find(params[:id]) 
@user = @instructor_profile.user 
+0

嗨Thaha。我认为你对这个问题是正确的。但是,我不确定为什么我需要在UsersController中定义关于instructor_profile的任何信息。也许我不完全理解has_one关联。但我认为,仅仅因为用户has_one instructor_profile,并不意味着每个用户都必须有一个instructor_profile。这不准确吗? – mattq 2013-04-25 00:56:35

+0

此外,我只是为这两个控制器添加了我的新&创建操作,供您查看。谢谢! – mattq 2013-04-25 01:12:53

+0

看到编辑的部分.. – 2013-04-25 06:54:18