Teej
Teej

Reputation: 12873

Why are the instance variables not set on the class using attr_accessor?

I tried to call an existing class using FileSearchable.new(current_user, params[:keyword]).call but I am getting the error, undefined method 'where' for nil:NilClass on my_folders = my_folders.where("name ILIKE ?", filter) unless filter.blank?

The class is below

class FileSearchable

  attr_accessor :user, :my_files, :my_folders, :shared_folders, :shared_files, :filter

  def initialize(user, filter)
    @user = user
    @my_folders = user.folders
    @my_files = user.user_documents
    @shared_folders = user.shared_folders
    @shared_files = user.user_documents
    @filter = filter
  end

  def apply_search_params
    my_folders = my_folders.where("name ILIKE ?", filter) unless filter.blank?
  end
end

I am not sure why the my_folders variable is not being set.

Upvotes: 0

Views: 62

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

It's a very common gotcha. You create a local variable my_folders which shadows your accessor. Call the method explicitly:

  def apply_search_params
    self.my_folders = my_folders.where("name ILIKE ?", filter) unless filter.blank?
  end

Or assign the instance var directly (like you do in the initializer)

  def apply_search_params
    @my_folders = my_folders.where("name ILIKE ?", filter) unless filter.blank?
  end

But this somewhat defeats the purpose of attr_accessor. Why generate a writer and then not use it?

Upvotes: 2

Related Questions