beaconhill
beaconhill

Reputation: 451

Accessing variables from multiple models

I have six distinct sections of my Rails application, all of which have their own models, views, and controllers.

I'm trying to create a "dashboard" page that accesses variables from each of the sections. For instance, in one of my controllers, I have this condition:

if @retirementsavingsdiff < 0
  @retiregrade = "pass"
end

I can't seem to access this variable from a different view/controller though.

Do I put my dashboard logic in application_controller.rb?

Upvotes: 1

Views: 508

Answers (3)

James Mason
James Mason

Reputation: 4306

A good option for making code reusable is separating it out into modules. Rails 4 includes something called Concerns that make this really easy. Here's a blog post with a good illustration of using Concerns for Controllers, and here's a sample of what your code might look like:

# /app/controllers/concerns/retirement_grade_checker.rb
module RetirementGradeChecker
  extend ActiveSupport::Concern

  def check_retire_grade
    @retirementsavingsdiff = params[:retirementsavingsdiff]
    if @retirementsavingsdiff < 0
      @retiregrade = "pass"
    end
  end
end

# /app/controllers/retirement_controller.rb
class RetirementController < ApplicationController
  include RetirementGradeChecker

  def index
    check_retire_grade
    #... other stuff
  end
end

# /app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
  include RetirementGradeChecker

  def index
    check_retire_grade
    #... other stuff
  end
end

Upvotes: 3

Chris Ledet
Chris Ledet

Reputation: 11628

I would avoid using view helpers and instead create a new class or module with all of your logic inside. By doing that you can reuse that logic whenever you need it.

Why do this instead of helpers? You can easily test it.

Upvotes: 1

Wally Ali
Wally Ali

Reputation: 2508

methods defined inside helpers are automatically available across all views.

if you want to convert a method defined inside the controller to a helper method, you can do that too:

def my_method
  # code
end

 helper_method :my_method

UPDATE:

here is an example from API

class ApplicationController < ActionController::Base
  helper_method :current_user, :logged_in?

  def current_user
    @current_user ||= User.find_by(id: session[:user])
  end

  def logged_in?
    current_user != nil
  end
end

Upvotes: 0

Related Questions