473b57acbf0d02127db3d2af78dffaca

I think there's a way to do this in rails using nested includes, and I spent a little while trying to figure it out, but I'm stumped.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class User < ActiveRecord::Base
  
  has_many :orders

  # wondering if there's a way to refactor this to not use :finder_sql
  has_many :purchased_downloads,
           :class_name => "Product",
           :finder_sql => "SELECT products.* FROM users 
                           INNER JOIN orders ON users.id = orders.user_id
                           INNER JOIN order_products ON order_products.order_id = orders.id
                           INNER JOIN products on order_products.product_id = products.id
                           WHERE users.id = 2 AND orders.state='paid' AND products.downloadable=1"
end


# as close as I got, returns the order, but what i want are the products

has_many :purchased_downloads, 
         :class_name => "Order", 
         :include => [:order_products => :product],
         :conditions => "orders.state='paid' AND products.downloadable=1"

# the relevant class relationships

class Order
  has_many :order_products
end

class OrderProduct
  belongs_to :product
end

Refactorings

No refactoring yet !

880cbab435f00197613c9cc2065b4f5a

danielharan

July 23, 2008, July 23, 2008 01:42, permalink

No rating. Login to rate!

Here's where I'd see it going - not clear if a named_scope can be used instead of a delegate call, or how to keep the knowledge of :paid? in order and :downloadable? in product.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class User < ActiveRecord::Base
  has_many :orders
  has_many :products, :through => :orders

  def downloads
    products.downloadable.collect(&:paid?)
  end
end

class Order
  has_many :products
end

class Product
  belongs_to :order
  named_scope :downloadable, :conditions => {:downloadable => true}
  delegate :paid?, :to => :order
end

Your refactoring





Format Copy from initial code

or Cancel