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?
-
Your instance variables will last a single request, you can use a before filter to save repeating yourself.Lee Jarvis– Lee Jarvis2012-01-02 18:24:44 +00:00Commented Jan 2, 2012 at 18:24
-
@Berlin Thanks for the reply.. I just asked if any you have.Arup Rakshit– Arup Rakshit2015-05-08 08:29:52 +00:00Commented May 8, 2015 at 8:29
Add a comment
|
1 Answer
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.