A better place for such logic is the model, to make things simpler and cleaner.
#SitesController
def index
@sites = Site.scope_filtered(params)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @sites }
end
end
#Site model
def self.scope_filtered(args)
result = if args[:program_id]
? where(program_id: args[:program_id])
else
: joins(program: :user)
end
result = result.tagged_with(args[:tags].split(' ')) if args[:tags]
result = result.page(args[:page]) if args[:page]
end
Side note: I'm not very sure what :user
is in joins(:program =>:user)
. I assume it will work according to original code.