Skip to main content
deleted 77 characters in body
Source Link
Billy Chan
  • 219
  • 1
  • 5

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.

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.

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 = args[:program_id] ? where(program_id: args[:program_id]) : joins(program: :user)
  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.

Source Link
Billy Chan
  • 219
  • 1
  • 5

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.