Clifton Labrum
Clifton Labrum

Reputation: 14068

Model Access throughout Entire Rails Application

Ruby 1.9.3 + Rails 3.2.8

I have a view that is rendered on every page in my app inside a partial:

<span id="sync-time">      
  <%= @sync.dropbox_last_sync.strftime('%b %e, %Y at %H:%M') %>
</span>

In order to use my syncs model and have access to the dropbox_last_sync method, I have to include it in every controller throughout my app. For example:

class EntriesController < ApplicationController
  def index
    @sync = current_user.sync
  end
end

...

class CurrenciesController < ApplicationController
  def index
    @sync = current_user.sync
  end
end

...etc.

Is there a way I can make the syncs model available everywhere by including it in my Application Controller somehow?

Upvotes: 0

Views: 38

Answers (2)

Niall Paterson
Niall Paterson

Reputation: 3580

This is better:

class ApplicationController < ActionController::Base
  before_filter :authenciate_user!
  before_filter :index

  def index
    @sync = current_user.sync
  end
end

You're using current_user always, so you need to have before_filter :authenciate_user! here aswell and above the other one.

Upvotes: 0

Shadwell
Shadwell

Reputation: 34774

You should be able to add a before_filter in your application controller:

before_filter :setup_sync

def setup_sync
  if current_user
    @sync = current_user.sync
  end
end

You need to be careful that your setup_sync filter runs after whatever code you are using to set up your current_user. This is probably another before_filter though so provided you have before_filter :setup_sync declared after your current user filter it will work fine.

Upvotes: 2

Related Questions