I hope this is the right kind of question to ask here; I can’t find any info on this specific question, but I am not sure what to search on.
Is there a best practice around how to write the much-duplicated ‘find’ in the controller?
Here are a couple standard methods:
def show
@object = Object.find(params[:id])
...
respond_with @object
end
def edit
@object = Object.find(params[:id])
...
respond_with @object
end
I’ve seen this moved to a before_filter like this:
before_filter :find_object, only: [:show, :edit]
...
def show
...
respond_with @object
end
def edit
...
respond_with @object
end
...
private
def find_object
@object = Object.find(params[:id])
end
And also calling the method directly, setting the @var the first time, and just referencing it from then on:
def show
...
respond_with object
end
def edit
...
respond_with object
end
...
private
def object
@object ||= Object.find(params[:id])
end
Is there any preference of what works best? Any downside to either of these methods? I find both refactorings to be kind of more confusing than helpful, but if something is common practice, OR if one is just a better way to write the code, it’ll just be a matter of getting used to it going forward.