0

I'm trying to get the following code to work, but it's giving me an undefined variable error:

class PagesController < ApplicationController
  @company = "Acme"
  def home
    @title = "Welcome to #{company}"
  end
  def faq
    @title = "FAQ | #{company}"
  end
end

How do I access @company within functions?

methodofaction
  • 70,885
  • 21
  • 151
  • 164

2 Answers2

3

As in Ruby, every class is an object too, what you are doing here is setting an instance variable named @company on the class object PagesController, not on an instance of PagesController.

What you may want is to use a constant instead of the instance variable. Maybe like this:

class PagesController < ApplicationController
  COMPANY = "Acme"

  def home
    @title = "Welcome to #{COMPANY}"
  end

  def faq
    @title = "FAQ | #{COMPANY}"
  end
end

If you want the company to change dependent of what "page" you are displaying, you should consider adding a Page model which has an attribute which holds the company name or an association to another model named Company.

aef
  • 4,498
  • 7
  • 26
  • 44
0

You can access it directly like this

class PagesController < ApplicationController
  @@company = "Acme"  # class var
  def home
    @title = "Welcome to #{@@company}"
  end
  def faq
    @title = "FAQ | #{@@company}"
  end
end

Or define a custom getter method like this

class PagesController < ApplicationController
  @@company = "Acme"
  def home
    @title = "Welcome to #{company}"
  end
  def faq
    @title = "FAQ | #{company}"
  end
  private
  def company
    @@company
  end
end

Or get Company name from database

class PagesController < ApplicationController
  def home
    @title = "Welcome to #{company}"
  end
  def faq
    @title = "FAQ | #{company}"
  end

  private
  def company
    @company ||= current_user.company  # get company of logged in user (and "cache" it)
    @company.name
  end
end
maček
  • 76,434
  • 37
  • 167
  • 198