Ok, lets start over.
Here are my models:
PHP Code:
class Article < ActiveRecord::Base
belongs_to :author
has_many :collections, :through => :collection_items
end
class Author < ActiveRecord::Base
has_many :articles
has_many :collections
end
class Collection < ActiveRecord::Base
has_many :articles, :through => :collection_items
belongs_to :author
def add(article)
articles << article
end
def remove(article)
if articles.detect{|i| i == article}
articles.delete(article)
end
end
end
class CollectionItem < ActiveRecord::Base
belongs_to :article
belongs_to :collection
end
Here are my fixtures:
collection_items.yml
PHP Code:
item1:
article_id: 1
collection_id: 1
stacking_order: 1
item2:
article_id: 2
collection_id: 1
stacking_order: 2
item3:
article_id: 1
collection_id: 2
stacking_order: 1
articles.yml
PHP Code:
article1:
id: 1
author_id: 1
keywords: web development
body: This is an article about web design and development with Ruby
article2:
id: 2
author_id: 2
keywords: something
body: This is an article about something else
collections.yml
PHP Code:
collection1:
id: 1
author_id: 1
name: newsletter
collection2:
id: 2
author_id: 1
name: webpage
And here's a test that fails...
PHP Code:
fixtures :collections, :articles, :collection_items
def test_how_many_articles
result = Collection.find(1)
assert_equal 2, result.articles.length
end
with this error:
PHP Code:
test_how_many_articles(TestCollection):
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :collection_items in model Article
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/reflection.rb:169:in `check_validity!'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/associations/has_many_through_association.rb:6:in `initialize'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/associations.rb:865:in `new'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/associations.rb:865:in `articles'
/usr/lib/ruby/gems/1.8/gems/activerecord-1.14.0/lib/active_record/associations.rb:860:in `articles'
./test/unit/test_collection.rb:22:in `test_how_many_articles'
What am I missing here? Am I not understanding has_many :through or is this a bug?
Bookmarks