3

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?

2
  • Your instance variables will last a single request, you can use a before filter to save repeating yourself. Commented Jan 2, 2012 at 18:24
  • @Berlin Thanks for the reply.. I just asked if any you have. Commented May 8, 2015 at 8:29

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.