Hey I' m quite surprised by the behaviour of has_many associations on new_records, so might someone here tell me if I'm simply missing the point or is it a Bug?
ruby 1.9.3p265 Rails 3.2.8 class Invoice < ActiveRecord::Base has_many :bikes, :dependent => :nullify end class Bike < ActiveRecord::Base belongs_to Invoice end now a bike does not necessarily belongs to any invoice, so a bike with invoice_id = nil is perfectly valid. If I now create a new Invoice and ask for its bikes, everything works as expected: ruby-1.9.3-head :001 > Invoice.new.bikes => [] To my surprise now: ruby-1.9.3-head :002 > Invoice.new.bikes.count (1.9ms) SELECT COUNT(*) FROM "bikes" WHERE "bikes"."invoice_id" IS NULL => 744 and even better (Bike has an attribute :price) ruby-1.9.3-head :003 > Invoice.new.bikes.sum(&:price) Bike Load (30.4ms) SELECT "bikes".* FROM "bikes" WHERE "bikes"."invoice_id" IS NULL => 809577.5 Well I see that the sql is perfectly logical, but nonetheless not very practical. Do I really have to do something ugly like class Invoice < ActiveRecord::Base has_many :bikes, :dependent => :nullify, :conditions => 'invoice_id IS NOT NULL' end or do I simply miss the point? cheers robbytobby -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-core/-/kL11IVcm0DQJ. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
