2016-12-09 4 views
0

私はRailsでアプリケーションを構築しています。私は "Users"というテーブルと "Profiles"というテーブルを持っています。各ユーザーhas_oneプロファイル。各プロファイルはユーザーに属します。私は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

あなたも私たちにユーザーとプロフィールのモデルを表示できますか? エラーが1つまたは複数のユーザーがプロファイルを持っていないので、あなたもu.profile.name if user.profile.present?

(私の意見では最悪)とユーザーに関するu.profile.try(:name)かのような方法を使用することができます表示されます - プロファイルのプロパティ、ここでは、このトピックdelegate、または場合についてgreateの記事ですあなたはこれを使用したくないのですか?

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

ありがとうございました!はい、問題は一部のユーザーがプロファイルを持っていないことでした。 –

関連する問題