Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Controller Variables in Rails

I have a ChatController and an @user variable in it. On the main page I display @user.name. I also have destroy and create methods that work with ajax, so when I delete a message from my chat, @user becomes nil. To prevent problems from calling name on a nil object, I can add @user=User.find_by_id(:user_id) to every method. But this becomes tedious if I have many methods. Can I declare @user=User.find_by_id(:user_id) once and DRY up my code?

like image 606
Kindoloki Avatar asked Feb 22 '26 15:02

Kindoloki


1 Answers

Yes, this is done in a before_filter (Documentation).

Something like:

class ChatController < ActionController::Base
  before_filter :find_user


  private
  def find_user
    @user ||= User.find_by_id(params[:user_id])
  end
end

You may also consider using Inherited Resources which automates this for you.

like image 107
AndrewF Avatar answered Feb 25 '26 06:02

AndrewF