ruby on rails 3范围扩展和包括

时间:2011-05-11 00:36:46

标签: ruby ruby-on-rails-3 activerecord scope

我正在尝试范围扩展,并且想知道我是否可以做这样的事情。

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方法?

干杯,

2 个答案:

答案 0 :(得分:1)

我认为您需要将includes语句移动到lambda中

class User  
  has_many :tasks
  belongs_to :klass      

  scope :users_in_klass, lambda {|k| includes(:tasks).where(:klass_id => k)} do

    def current_task_report
      users = []
      each {|u|
        user = {
          :name => u.full_name,
          :id => u.id,
          :tasks => u.tasks
        }
        users << user
      }
      users
    end

end

答案 1 :(得分:0)

如何将此关联添加到您的Klass:

class Klass < ActiveRecord::Base

  has_many :users
  has_many :tasks, :through => :users

end

然后获取当前任务报告将如下所示:

Klass.find(6899).tasks

我假设Rails会足够聪明,可以在生成的查询中自动执行“IN”语句。