add self referential has_many :through example [Rick]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4006 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
Rick Olson 2006-03-21 01:07:16 +00:00
parent d15550aecc
commit c8470f8a5b
4 changed files with 29 additions and 2 deletions

View File

@ -9,7 +9,7 @@ require 'fixtures/categorization'
class AssociationsJoinModelTest < Test::Unit::TestCase class AssociationsJoinModelTest < Test::Unit::TestCase
self.use_transactional_fixtures = false self.use_transactional_fixtures = false
fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites
def test_has_many def test_has_many
assert_equal categories(:general), authors(:david).categories.first assert_equal categories(:general), authors(:david).categories.first
@ -294,6 +294,17 @@ class AssociationsJoinModelTest < Test::Unit::TestCase
end end
end end
def test_self_referential_has_many_through
assert_equal [authors(:mary)], authors(:david).favorite_authors
assert_equal [], authors(:mary).favorite_authors
end
def test_add_to_self_referential_has_many_through
new_author = Author.create(:name => "Bob")
authors(:david).author_favorites.create :favorite_author => new_author
assert_equal [new_author, authors(:mary)], authors(:david).reload.favorite_authors
end
private private
# create dynamic Post models to allow different dependency options # create dynamic Post models to allow different dependency options
def find_post_with_dependency(post_id, association, association_name, dependency) def find_post_with_dependency(post_id, association, association_name, dependency)

View File

@ -25,9 +25,12 @@ class Author < ActiveRecord::Base
has_many :categorizations has_many :categorizations
has_many :categories, :through => :categorizations has_many :categories, :through => :categorizations
has_many :nothings, :through => :kateggorisatons, :class_name => 'Category' has_many :nothings, :through => :kateggorisatons, :class_name => 'Category'
has_many :author_favorites
has_many :favorite_authors, :through => :author_favorites, :order => 'name'
belongs_to :author_address belongs_to :author_address
attr_accessor :post_log attr_accessor :post_log
@ -60,4 +63,9 @@ end
class AuthorAddress < ActiveRecord::Base class AuthorAddress < ActiveRecord::Base
has_one :author has_one :author
end
class AuthorFavorite < ActiveRecord::Base
belongs_to :author
belongs_to :favorite_author, :class_name => "Author", :foreign_key => 'favorite_author_id'
end end

View File

@ -0,0 +1,4 @@
david_mary:
id: 1
author_id: 1
favorite_author_id: 2

View File

@ -25,4 +25,8 @@ ActiveRecord::Schema.define do
t.column :author_address_id, :integer t.column :author_address_id, :integer
end end
create_table :author_favorites, :force => true do |t|
t.column :author_id, :integer
t.column :favorite_author_id, :integer
end
end end