什么是Rails 3链式方法来进行这种查询?
@jobs_by_location =
Employer.find_by_sql ['SELECT count(j.id) AS job_count, e.* FROM employers e, jobs j' +
' WHERE e.parent_id = ? AND j.employer_id = e.id' +
' AND j.status = 2' +
' GROUP BY e.id' +
' ORDER BY e.state_id, e.city, e.name ASC', @employer.id]
我提出了:
@jobs_by_location = Employer
.select('employers.*, count(jobs.id) as job_count').joins(:jobs)
.group('employers.id').order('employers.state_id,employers.city,employers.name ASC')
.where(:jobs => {:status => 2}).where(@employer.id)
我可以进一步收紧吗?我可以清理order()调用,我应该在某处使用count()吗?我应该打扰吗?谢谢.
最佳答案 在order子句中,除非列名不明确,否则不需要指定表.你可能只是这样做
.order('state_id, city, name ASC')
另外,我认为你打算放
.where(:parent_id => @employer.id) # instead of .where(@employer.id)
除此之外,我认为你的事情很好.我不认为.count会帮助你解决这个问题.