2016-08-23 8 views
2

두 테이블이 있습니다. UserAccount, Account belongs_to User입니다. 'about'필드 (표 Accounts)에서 값을 얻으려는 경우 nil:NilClass '에'undefined methodabout '의 문제가 있습니다. 문제는 팔로어 목록을 가져 와서 자신의 아바타 또는 정보를 다른 테이블에서 가져 와서보기로 출력하는 것입니다.정의되지 않은 메소드 'about'for nill 클래스

컨트롤러 내 방법

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

%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

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

실행'레일, 그리고'user.account.nil를 실행', 답에 해당하는 경우 : 이 시도 할 수 있습니다? 신규 사용자는 생성되는 기본 계정이 없으므로이를 작성해야합니다. 나는 그 대답을 게시 할 것입니다. – amingilani

+0

예, 대답은 사실입니다 – Gaka

답변

1

저는 모든 사용자가 계정을 갖고있는 것은 아닙니다. `사용자 = User.create를 통해 새로운 사용자 ( )를`만들 console`

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

네, 저의 경우에는 고마워요! – Gaka