I''ve got a has_many :through setup that works, but has a rub to
it. This behavior happens with rel_1-1-0 *and* trunk (4169).
Here are the models:
class Product < ActiveRecord::Base
has_many :cart_items
has_many :accounts, :through => :cart_items
class CartItem < ActiveRecord::Base
belongs_to :account
belongs_to :product
class Account < ActiveRecord::Base
has_many :cart_items
has_many :products, :through => :cart_items do
def in_cart
find :all, :conditions => ["order_id IS NULL"]
end
def previously_bought
find :all, :conditions => ["order_id IS NOT NULL"]
end
end
Here is the test that triggers the issue:
def test_add_to_freds_cart
fred = Account.find_by_login("fred")
product = Product.create(:sku => "XXXX",
:short_name => "Fred''s
product!",
:retail_price => Money.new(19291),
:wholesale_price => Money.new(17291),
:currency => "USD")
assert_equal 0, fred.products.in_cart.size
assert_equal 0, product.accounts.size
cart_item = CartItem.create(:quantity => 3, :unit_price =>
Money.new(3000))
fred.cart_items << cart_item
product.cart_items << cart_item
cart_item.save
breakpoint
assert_equal 1, fred.products.in_cart.size
assert_equal 1, product.accounts.size
end
When the breakpoint is hit, cart_items has a new row which
references this new product, and fred.
>>> CartItem.find_all("product_id = 15")
=> [#<CartItem:0x2207710... "account_id"=>"5"...
"product_id"=>"15"...]
But look at what happens:
>>> fred.products
=> [#<Product:0x223c028.... "id"=>"15"...]
>>> product.accounts
=> []
product.accounts *should* contain fred, shouldn''t it? When I
enter that line, no query is performed on the database. The
only way I can get him to show up is to retrieve product again:
>>> Product.find(15).accounts
=> [#<Account:0x2226fc0.... "login"=>"fred"...]
Is this a bug, or am I missing some elementary principle of
has_many?
Thanks.
-Drew