在 Rails 查询中组合 Presenter 和 #includes
Combining Presenters and #includes in Rails query
假设我的 Rails4 应用程序中有以下设置:
一个学生 has_many
个学位,一个学位 belongs_to
个学生。我也有一个 StudentPresenter 和一个 DegreePresenter 对应于这两个模型。 (主持人 as defined here)
我要查询以下内容:
student_ids = [1,2,3,4]
students = Student.where(id: student_ids).includes(:degrees)
但我想访问 Student 和 Degree 的 Presenter 方法。
如何使用 Presenter 预加载数据?
Rails 4.1.5
您链接到的博客 post 中的演示者只是简单的 ruby 对象,在创建新演示者时将模型作为参数之一:
所以要创建 StudentPresenters:
students = Student.where(id: student_ids).includes(:degrees)
decorated_students = students.map { |s| StudentPresenter.new(s, view_context) }
然后你可以在 StudentPresenter
中添加一个 returns 修饰度的方法;
class StudentPresenter < BasePresenter
def degrees
@model.degrees.map { |d| DegreePresenter.new(d, @view) }
end
end
已添加
这如何与预加载一起使用?由于您使用的是 includes
With includes, Active Record ensures that all of the specified
associations are loaded using the minimum possible number of queries.
Rails 应尽快加载学生 table 和学位 students.map
.
假设我的 Rails4 应用程序中有以下设置:
一个学生 has_many
个学位,一个学位 belongs_to
个学生。我也有一个 StudentPresenter 和一个 DegreePresenter 对应于这两个模型。 (主持人 as defined here)
我要查询以下内容:
student_ids = [1,2,3,4]
students = Student.where(id: student_ids).includes(:degrees)
但我想访问 Student 和 Degree 的 Presenter 方法。
如何使用 Presenter 预加载数据?
Rails 4.1.5
您链接到的博客 post 中的演示者只是简单的 ruby 对象,在创建新演示者时将模型作为参数之一:
所以要创建 StudentPresenters:
students = Student.where(id: student_ids).includes(:degrees)
decorated_students = students.map { |s| StudentPresenter.new(s, view_context) }
然后你可以在 StudentPresenter
中添加一个 returns 修饰度的方法;
class StudentPresenter < BasePresenter
def degrees
@model.degrees.map { |d| DegreePresenter.new(d, @view) }
end
end
已添加
这如何与预加载一起使用?由于您使用的是 includes
With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
Rails 应尽快加载学生 table 和学位 students.map
.