沿着[url=http://hideto.iteye.com/blog/105774]Rails宝典之第三式: 通过关联做查询[/url]的脚步,我们可以进一步简化代码:
[code]
class Task < ActiveRecord::Base
belongs_to :project
def self.find_incomplete
find_all_by_complete(false, : order => 'created_at DESC')
end
end
class ProjectsController < ApplicationController
def show
@project = Project.find(param[:id])
@tasks = @project.tasks.find_incomplete
end
end
class TasksController < ApplicationController
def index
@tasks = Task.find_incomplete
end
end
[/code]
[code]
class Task < ActiveRecord::Base
belongs_to :project
def self.find_incomplete
find_all_by_complete(false, : order => 'created_at DESC')
end
end
class ProjectsController < ApplicationController
def show
@project = Project.find(param[:id])
@tasks = @project.tasks.find_incomplete
end
end
class TasksController < ApplicationController
def index
@tasks = Task.find_incomplete
end
end
[/code]
本文介绍了一种在Rails中通过关联查询来优化代码的方法。通过定义特定的查询方法,可以有效地减少查询复杂度并提高应用程序的性能。

被折叠的 条评论
为什么被折叠?



