2016-12-09 19 views
0

我在Rails中構建應用程序。我有一個名爲「Users」的表和一個名爲「Profiles」的表。每個用戶擁有一個配置文件。每個配置文件都屬於用戶。我正在嘗試使用profile_controller的索引頁面。我希望每個用戶個人資料都按他們登錄的順序顯示,但我有更多基本問題。首先,我有Rails應用程序中未定義方法的問題

@users = All.users 

在索引操作中定義。每個「配置文件」都有一個「名稱」屬性。在索引視圖,我試圖訪問通過@users此屬性

<% @users.each do |u| %> 
    <%= u.profile.name %> 
    <% end %> 

這帶來了這個錯誤「未定義的方法'名稱」的零:NilClass。」請注意,這樣做的工作:

<% @users.each do |u| %> 
    <%= u.last_sign_in_at %> 
    <% end %> 

我想通過「last_sign_in_at」制定財產「用戶,」否則我會簡單地使用配置文件對象直接組織的名稱。我還沒有開始訂購。有人可以幫忙嗎?我希望能夠通過@users實例變量訪問配置文件屬性。這是我的模式:

create_table "profiles", force: :cascade do |t| 
t.datetime "created_at",   null: false 
t.datetime "updated_at",   null: false 
t.integer "age" 
t.string "status" 
t.string "location" 
t.string "bio" 
t.string "primary_instrument" 
t.string "second_instrument" 
t.string "third_instrument" 
t.string "name" 
t.integer "user_id" 
t.string "looking_for" 
end 

create_table "users", force: :cascade do |t| 
t.string "email",     default: "", null: false 
t.string "encrypted_password",  default: "", null: false 
t.string "reset_password_token" 
t.datetime "reset_password_sent_at" 
t.datetime "remember_created_at" 
t.integer "sign_in_count",   default: 0, null: false 
t.datetime "current_sign_in_at" 
t.datetime "last_sign_in_at" 
t.string "current_sign_in_ip" 
t.string "last_sign_in_ip" 
t.datetime "created_at",       null: false 
t.datetime "updated_at",       null: false 
t.index ["email"], name: "index_users_on_email", unique: true 
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 

回答

2

你能告訴我們也用戶和配置文件模型? 錯誤出現,因爲一個或多個用戶沒有配置文件,您還可以使用方法如u.profile.try(:name)或(最壞的在我看來)u.profile.name if user.profile.present?

而關於用戶 - 配置文件屬性,這裏是這個話題delegate,或者如果馬麗娟文章你不想用這個,你可以做點像

#user Model 
def name 
    profile.try(:name) 
end 
+0

謝謝先生!是的,問題是一些用戶沒有配置文件。 –

相關問題