开发者

ruby on rails 3 scope extensions and includes

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


I think you need to move the includes statement into your 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


What about adding this association to your Klass:

class Klass < ActiveRecord::Base

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

end

Then getting the current task report would look something like this:

Klass.find(6899).tasks

I am assuming Rails will be smart enough to automatically do an "IN" statement in the resulting query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜