2013-04-24 86 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