2016-08-23 10 views
2

のために私は2つのテーブルを持っています。フィールド 'about'(テーブルAccounts)から値を取得したい場合は、nil:NilClass 'に対して' undefined methodabout 'という問題があります。課題は、フォロワーのリストを取得し、別のテーブルからアバターや情報を取得してViewに出力することです。未定義のメソッドは、nillクラス

%h1 My followers 
- @followers.each do |f| 
    %ul.list-group 
    %li.list-group-item 
     %p=f.name 
     %p=f.account.about 
%h1 I'm follower 
- @followables.each do |followable| 
    %ul.list-group 
%li.list-group-item 
    %p=followable.name 
    %p=followable.account.about 

list_of_follower.html.hamlコントローラ

def list_of_follower 
    @followers_id = Follow.select("follower_id ").where("followable_id = ?", current_user) 
    @followers = User.where("id in (?)", @followers_id) 
    @followables_id = Follow.select("followable_id").where("follower_id = ?", current_user) 
    @followables = User.where("id in (?)", @followables_id) 
end 

ビューでの私の方法Create_Accounts.rb

class CreateAccounts < ActiveRecord::Migration 
    def change 
    create_table :accounts do |t| 
     t.belongs_to :user, index: true 
     t.text :about 
     t.timestamps null: false 
    end 
end 
end 

User.rb

class User < ActiveRecord::Base 
acts_as_followable 
acts_as_follower 
acts_as_liker 
has_one :account 
has_many :posts 
has_many :comments 

accepts_nested_attributes_for :account 
devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

def email_required? 
    false 
end 

def email_changed? 
    false 
end 

validates :login, :email, uniqueness: true 
end 

Account.rb

class Account < ActiveRecord::Base 
belongs_to :user 
    mount_uploader :avatar, AvatarUploader 
end 

テーブルUser内容が問題(作業要求)なしで表示されますが、それに関連付けられたテーブルの内容が表示されていない、問題は何ですか?

+0

ラン' 'レール、答えが真である場合、: あなたはこれを試すことができますか?新規ユーザーにはデフォルトアカウントが作成されていないため、作成する必要があります。私はその答えがあれば投稿します。 – amingilani

+0

はい、答えは真です – Gaka

答えて

1

私は問題はすべてのユーザーがアカウントを持っているとは限りません。 `ユーザー= User.create( )`を経由して、新規ユーザーを作成し、 `user.account.nilを実行console`

%p=f.account.try(:about) 
+0

はい、それは私の場合、ありがとう! – Gaka

関連する問題