2016-08-23 80 views
2

我有两个表:User有一个Account, Account belongs_to User。当我想从字段'about'(表Accounts)获得一些值时,我的问题'undefined methodabout'为nil:NilClass'。我们面临的挑战是获取关注者列表,并从另一个表中获取他们的头像或信息“about”并将其输出到View中。未定义的方法'约'为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 

查看list_of_follower.html.haml

%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 

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

运行'轨console'通过创建用户'= User.create新用户()',运行''user.account.nil,如果答案是真的,?新用户没有创建默认帐户,因此您必须创建该帐户。如果是这种情况,我会发布这个答案。 – amingilani

+0

是的,回答是真的 – Gaka

回答

1

我认为,一个问题不是每个用户都有一个帐户。 你可以试试这个:

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

是的,这是我的情况,谢谢! – Gaka