ruby on Rails 3 范围扩展并包括
我正在尝试范围扩展,想知道是否可以做这样的事情。
class User
has_many :tasks
belongs_to :klass
scope :users_in_klass, lambda {|k| where(:klass_id => k)} do
def current_task_report
includes(:tasks)
users = []
each {|u|
user = {
:name => u.full_name,
:id => u.id,
:tasks => u.tasks
}
users << user
}
users
end
end
并这样称呼它
u = User.users_in_klass(6899)
u.current_task_report
我遇到的问题是它忽略了急切加载任务中的包含内容。
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE (`users`.`klass_id` = 6899)
Task Load (0.4ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 46539)
Task Load (0.2ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 46909)
Task Load (0.2ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 46910)
我正在做的事情正确吗?
顺便说一句,是否有更好的地方来放置 current_task_report 方法?
干杯,
蒂姆
I am experimenting with scope extensions and was wondering if I could do something like this.
class User
has_many :tasks
belongs_to :klass
scope :users_in_klass, lambda {|k| where(:klass_id => k)} do
def current_task_report
includes(:tasks)
users = []
each {|u|
user = {
:name => u.full_name,
:id => u.id,
:tasks => u.tasks
}
users << user
}
users
end
end
And call it like this
u = User.users_in_klass(6899)
u.current_task_report
The problem I'm having is that it's ignoring the includes on the tasks for eager loading.
User Load (0.5ms) SELECT `users`.* FROM `users` WHERE (`users`.`klass_id` = 6899)
Task Load (0.4ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 46539)
Task Load (0.2ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 46909)
Task Load (0.2ms) SELECT `tasks`.* FROM `tasks` WHERE (`tasks`.user_id = 46910)
Is what I'm am doing correct?
On a side note, Is there a better place to put the current_task_report method?
Cheers,
Tim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你需要将包含语句移到你的 lambda 中
I think you need to move the includes statement into your lambda
将这个关联添加到您的 Klass 中怎么样:
然后获取当前任务报告将如下所示:
我假设 Rails 足够聪明,可以在结果查询中自动执行“IN”语句。
What about adding this association to your Klass:
Then getting the current task report would look something like this:
I am assuming Rails will be smart enough to automatically do an "IN" statement in the resulting query.