Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

has_many :through Doesn't Use Conditions For Creating New Records

#2090

has_many :through Doesn't Use Conditions For Creating New Records. Assuming the following ActiveRecord:


class Post < ActiveRecord::Base
  has_many :skimmers, :class_name => 'Reader', :conditions => { :skimmer => true }
  has_many :impatient_people, :through => :skimmers, :source => :person

end

When a new record is created with the following code:


my_post.impatient_people.create!(:first_name => 'bob')

Creates the proper models in the readers and people tables but the record in the readers table does not have the skimmer attribute set to true. The attached patch will interrogate the conditions options and if it's a hash, add it to the attribute hash when creating the join model.

Reported by Matt Bauer · February 27th, 2009 @ 12:20 AM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Matt Bauer
  2. Josh Susser
    Josh Susser
    • Tag changed from activerecord, has_many_through to activerecord, has_many_through, patch

    While it's possible to create sets of conditions where this will work, you can also easily create ones where they don't. Just try an inequality test and you'll see. e.g. ["published_at < ?", 1.year.ago]. I think coming up with a way to do the right thing while avoiding surprises is going to be very difficult.

    March 3rd, 2009 @ 03:59 AM

  3. Matt Bauer
    Matt Bauer

    I completely agree with you which is why this patch only works when there is a hash provided. This will avoid surprises though I agree it may be to subtle yet.

    March 3rd, 2009 @ 04:10 AM

  4. Duncan McKee
    Duncan McKee

    +1 — As it is now, the create method on a has_many association does respect conditions as long as they are in hash form, and it is documented as such. The surprise is that, using the example above, post.skimmers.create creates a reader with skimmer==true, while post.impatient_people.<< creates a reader with skimmer==nil.

    March 3rd, 2009 @ 05:49 PM

  5. Pratik
    Pratik
    • State changed from new to resolved

    Resolved in 83c1934003740ed01c618a8943457a0df53e2adb

    June 21st, 2009 @ 05:43 PM

  6. Repository
  7. Repository