Search code examples
ruby-on-railsactiverecordnested-attributes

Undefined method 'about' for nill class


I have two table: User has one Account, Account belongs_to User. When I want to get some value from field 'about' (table Accounts), I have a problem 'undefined method about' for nil:NilClass'. The challenge is to get the list of followers and gain their avatar or information 'about' from another table and output it in View.

My method in controller

 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

View 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

table User content is displayed without problems (work requests), but the contents of the table associated with it does not displayed, what is the problem?


Solution

  • I think, a problem is not every user has an account. You can try this:

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