我想更好地结合发现者。
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
答案 0 :(得分:4)
假设您有以下型号:
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
现在您可以在控制器中使用search
方法:
Company.search(params)
答案 1 :(得分:2)
我是否遗漏了某些东西,或者归结为这一切?
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