What's the best way to stop repeating this line in my contro


I am trying to follow the “DRY” principle and came across a problem.
I am working on a small ajax task manager, and right now in the index
page which renders the list, I have (for example, in the Lists

def index
@lists = List.find(:all)

Now within the controller there’s also a list_add action which is
called via ajax…

def list_add
if List.create(params[:list])
@lists = List.find(:all)
render(:partial => “listform”)

I need to put the @lists = List.find(:all) in it again so it gets the
new updated list to render via AJAX like I did in the index action,
and I have to do this for every action I need…

Is there a way to do this so I can stop repeating myself? Or am I
outta luck?


use a :before_filter

at top of your controller:

before_filter :get_list

then add:

def get_list
@lists = List.find(:all)

now get_list will be called before index, list_add, or any other
methods. If you just want it for those two change the top line to:

before_filter :get_list, :only => [:index, :list_add]

you can also use :except => [ … ]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs