I have 2 nested resources in one of my Rails apps and the way the index is handled by the inner resources bothers me somewhat:
def index
@program = Program.approved.find(params[:program_id]) if params[:program_id]
if params[:tags]
tags = params[:tags].split(" ")
if @program
@sites = Site.where(:program_id => @program.id).tagged_with(tags).page(params[:page])
else
@sites = Site.joins(:program => :user).tagged_with(tags).page(params[:page])
end
else
if @program
@sites = Site.where(:program_id => @program.id).page(params[:page])
else
@sites = Site.joins(:program => :user).page(params[:page])
end
end
respond_to do |format|
format.html # index.html.erb
format.json { render json: @sites }
end
end
The complexity is caused because I want my Site
resource to be accessible both through it's Program
or directly. The results are also optionally filtered based on tags if they are included in the params
.
The joins are required because if a site belongs to a user then I display Edit/Delete
options.
It just doesn't feel like good Ruby code. So any refactoring tips would be helpful.