This project is archived and is in readonly mode.

#6066 ✓invalid
GreenPlastik

Finder conditions and includes are (still) ignored on has_many through

Reported by GreenPlastik | November 25th, 2010 @ 05:08 PM

Ruby 1.8.7-p302
Rails 3.0.3

Given two models Book and Person, a book can have many people as authors or editors. And a person can be an author and/or editor for many books. So you should be able to do @book.people, @book.authors, @book.editors, as well as @person.books, @author.books, and @editor.books (obviously only after setting up those instance variables first).

Similarly, the code below should allow you to do @book.authors.build and @book.editors.build.

Here are the models:

book.rb

class Book < ActiveRecord::Base
  has_many :book_people, :dependent => :destroy
  has_many :people, :through => :book_people, :uniq => true

  has_many :authors, :through => :book_people, :source => :person, :include => :book_people, :conditions => {'book_people.person_type' =>  'Author' } do
    def <<(author) 
      BookPeople.send(:with_scope, :create => { :person_type => "Author" } ) { self.concat author } 
    end 
  end

  has_many :editors, :through => :book_people, :source => :person, :include => :book_people, :conditions => {'book_people.person_type' =>  'Editor' } do
    def <<(editor) 
      BookPeople.send(:with_scope, :create => { :person_type => "Editor" } ) { self.concat editor } 
    end 
  end
end

person.rb

class Person < ActiveRecord::Base
  has_many :book_people, :dependent => :destroy
  has_many :books, :through => :book_people
end

book_person.rb

class BookPerson < ActiveRecord::Base
  belongs_to :person
  belongs_to :book

  belongs_to :author, :class_name => "Person", :foreign_key => :person_id
  belongs_to :editor, :class_name => "Person", :foreign_key => :person_id
end

Going to edit a book to add or change the authors and editors for the book, leads to the following error:

SQLite3::SQLException: no such column: book_people.person_type: SELECT "people".* FROM "people" WHERE ("book_people"."person_type" = 'Author')

Obviously, running that query directly against the DB fails with the same error. It doesn't seem to know about the 'book_people' table and its column 'person_type'.

It appears the ':include => :book_people' is being ignored. Furthermore, as the association is going through 'book_people' anyway, the include should be unnecessary. Removing it does not resolve the problem.

This issue is similar to the one marked as resolved in:
https://rails.lighthouseapp.com/projects/8994/tickets/1845-finder-m...

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Pages