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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With