0

如何在 Rails 中调用查询结果的方法我的项目控制器中有以下代码

def inprogress_report @projects = Project.all

@project_list = Project.find_by_sql("select p.id, p.name, (select sum(i.estimated_hours) from issues i where i.project_id = p.id) as estimate_hours,(select sum(t.hours) from time_entries t where p.id = t.project_id ) as Spent_Hours,(select u.firstname from users u where u.id IN(select user_id from members m where m.project_id = p.id and m.id IN (select member_id from member_roles where role_id IN (select id from roles r where r.name = 'Project Coordinator'))) limit 1) as Coordinator,(select u.firstname from users u where u.id IN(select user_id from members m where m.project_id = p.id and m.id IN (select member_id from member_roles where role_id IN (select id from roles r where r.name = 'Project Manager'))) 限制 1) 作为项目 p where p.status IN (' 16','14','15','17','18','19','20') 按 p.id 分组")

现在我想在@project_list 结果上进行搜索

所以我放了

@project_list = @project_list.search(params[:search]) 

在我的 project.rb 中有

def search(search)
  if search
    where('name LIKE ?', "%#{search}%")
  else
    find(:all)
  end
end

但给了我错误未定义的搜索方法......

我可以使用 Active Record::Base.connection.select_all 进行上述查询吗?结果我想进一步排序是否可能请指导我

4

2 回答 2

0

Maximilian Gaß 是对的,但由于重写方法调用可能需要一段时间,如果结果数组的大小合理find_by_sql,我将重写search方法调用以使用方法调用返回的数组。find_by_sql换句话说,而不是:

@project_list = @project_list.search(params[:search]) 

放一些类似的东西:

@project_list.keep_if{ |p| /.*#{params[:search]}.*/.match p.name }
于 2013-08-17T11:17:10.013 回答
0

find_by_sql 返回一个普通数组,而不是结果集。如果要向其中添加其他条件,则必须在没有 find_by_sql 的情况下构建查询。

http://apidock.com/rails/ActiveRecord/Base/find_by_sql/class

于 2013-08-16T12:45:43.837 回答