Skip to content

Commit 32d722c

Browse files
committed
Add tests for delegations to same model
1 parent 7f1f17d commit 32d722c

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

spec/db/models.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ class VirtualTotalTestBase < ActiveRecord::Base
55
end
66

77
class Author < VirtualTotalTestBase
8+
# basically a :parent_id relationship
9+
belongs_to :teacher, :foreign_key => :teacher_id, :class_name => "Author"
10+
has_many :students, :foreign_key => :teacher_id, :class_name => "Author"
811
has_many :books
912
has_many :ordered_books, -> { ordered }, :class_name => "Book"
1013
has_many :published_books, -> { published }, :class_name => "Book"
@@ -36,6 +39,9 @@ class Author < VirtualTotalTestBase
3639
virtual_sum :sum_recently_published_books_rating, :recently_published_books, :rating
3740
virtual_delegate :description, :to => :current_photo, :prefix => true, :type => :string
3841
virtual_delegate :description, :to => :fancy_photo, :prefix => true, :type => :string
42+
# delegate to parent relationship
43+
virtual_delegate :name, :to => :teacher, :prefix => true, :type => :string
44+
virtual_delegate :teacher_name, :to => :teacher, :prefix => true, :type => :string
3945

4046
# This is here to provide a virtual_total of a virtual_has_many that depends upon an array of associations.
4147
# NOTE: this is tailored to the use case and is not an optimal solution

spec/db/schema.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
self.verbose = false
55

66
create_table "authors", :force => true do |t|
7+
t.integer "teacher_id", :index => true
78
t.string "name"
89
t.string "nickname"
910
end

spec/virtual_delegates_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@
2626
expect(tcs.map(&:x)).to match_array([nil, 4])
2727
end
2828

29+
# NOTE: this is intentonally delegating to self. Testing table aliases
30+
it "double delegates to parent information" do
31+
g = Author.create(:name => "grand")
32+
p = Author.create(:name => "parent", :teacher_id => g.id)
33+
Author.create(:name => "c1", :teacher_id => p.id)
34+
Author.create(:name => "c2", :teacher_id => p.id)
35+
36+
ret = Author.select(:name, :teacher_teacher_name, :teacher_name).order(:id).where(:teacher_id => p.id)
37+
expect(ret.map { |c| [c.teacher_teacher_name, c.teacher_name, c.name]}).to eq([["grand", "parent", "c1"],["grand", "parent", "c2"]])
38+
end
39+
2940
context "invalid" do
3041
it "expects a ':to' for delegation" do
3142
expect do

0 commit comments

Comments
 (0)