rails can this model code be refactored?
I would like to combine the finders better.
if params[:sort]
if params[:sort] == 'industry_id'
if params[:industry_id]
@companies = Company.find_all_by_industry_id(params[:industry_id], :joins => "left join industries ind on industry_id = ind.id", :order => "ind.name" + " " + sort_direction)
else
@companies = Company.all(:joins => "left join industries ind on industry_id = ind.id", :order => "ind.name" + " " + sort_direction)
end
else
if params[:industry_id]
开发者_运维问答 @companies = Company.find_all_by_industry_id(params[:industry_id], :order => sort_column + " " + sort_direction)
else
@companies = Company.all(:order => sort_column + " " + sort_direction)
end
end
else
if params[:industry_id]
@companies = Company.find_all_by_industry_id(:joins => "left join industries ind on industry_id = ind.id", :order => "ind.name" + " " + sort_direction)
else
@companies = Company.all
end
end
Assuming you have following model:
class Company
belongs_to :industry
def self.search p
opt = {:conditions => {}}
opt[:order] = (p[:sort] == "industry_id") ? "industries.name" : p[:sort]
opt[:order]+= " " + (p[:sort_direction] || "ASC") if opt[:order].present?
opt[:conditions][:industry_id] = p[:industry_id] if p[:industry_id].present?
if (p[:sort] == 'industry_id') or p[:industry_id].present?
opt[:include] = :industry
end
all(opt)
end
end
class Industry
has_many :companies
end
Now you can use the search
method in your controller:
Company.search(params)
Am I missing something or does it all boil down to this?
sort_joins = { 'ind.name' => 'left join industries ind on industry_id = ind.id' }
if params[:sort] == 'industry_id' || !params[:sort]
sort_column = 'ind.name'
end
sort_column = nil if sort_column && !params[:industry_id]
options = { }
if sort_column
options[:sort] = "#{sort_column} #{sort_direction}"
options[:joins] = sort_joins[sort_column] if sort_joins[sort_column]
end
if params[:industry_id]
@companies = Company.find_all_by_industry_id(params[:industry_id], options)
else
@companies = Company.all(options)
end
精彩评论