Michael Victor Michael Victor - 3 months ago 19
Ruby Question

How do I create an instance variable in rails using OpenStruct

I would like to return facets along with the data in my controller. My code was :

def index
@people = Person.for_branch(session[:branch_id]).for_interests(params[:interest_search]).search_query(params[:search_term]).for_lead_sources(params[:lead_source_search]).page params[:page]
@organization = Organization.find(session[:organization_id])
@facets.total_count = Person.all.count
@facets.filtered_count = @people.count
respond_to do |format|
format.html
format.json {render partial: 'table.html', locals: { people: @people, organization: @organization, facets: @facets}}
end
end


However, I keep getting the error total_count is not defined.

undefined method `total_count=' for nil:NilClass


How can I fixed this?

Answer

I think you want to use OpenStruct variable.

require 'ostruct'
# ...

def index
  @people = Person.for_branch(session[:branch_id]).for_interests(params[:interest_search]).search_query(params[:search_term]).for_lead_sources(params[:lead_source_search]).page params[:page]
  @organization = Organization.find(session[:organization_id])

  @facets = OpenStruct.new # initializing OpenStruct instance
  @facets.total_count = Person.all.count
  @facets.filtered_count = @people.count
  respond_to do |format|
    format.html 
    format.json {render partial: 'table.html', locals: { people: @people, organization: @organization, facets: @facets}}
  end
end

Please note, that it is more convinient to use plain old Hash instead:

facets = {total_count: Person.all.count, filtered_count: @people.count}
respond_to do |format|
  format.html 
  format.json {render partial: 'table.html', locals: { people: @people, organization: @organization, facets: facets}}
end

and use it in your views like this:

total count is <%= facets[:total_count] %>