@@ -71,3 +71,85 @@ class Account < ActiveRecord::Base
71
71
File . delete ( @db_file ) if File . exist? ( @db_file )
72
72
end
73
73
end
74
+
75
+ describe 'active record has_one through' do
76
+ # Setup DB
77
+ before ( :all ) do
78
+ @db_file = "test_two.db"
79
+
80
+ # Open a database
81
+ db = SQLite3 ::Database . new @db_file
82
+
83
+ # Create tables
84
+ db . execute_batch <<-SQL
85
+ create table forests (
86
+ id int primary key,
87
+ name varchar(30)
88
+ );
89
+
90
+ create table trees (
91
+ id int primary key,
92
+ forest_id int,
93
+ name varchar(30),
94
+
95
+ FOREIGN KEY (forest_id) REFERENCES forests(id)
96
+ );
97
+
98
+ create table fruits (
99
+ id int primary key,
100
+ tree_id int,
101
+ name varchar(30),
102
+
103
+ FOREIGN KEY (tree_id) REFERENCES trees(id)
104
+ );
105
+ SQL
106
+
107
+ # Insert records
108
+ db . execute_batch <<-SQL
109
+ insert into forests values (1, 'sherwood');
110
+ insert into trees values (2, 1,'pine');
111
+ insert into fruits values (3, 2, 'pine nut');
112
+
113
+ insert into fruits(id,name) values (4,'apple');
114
+ SQL
115
+ end
116
+
117
+ # Setup Active Record
118
+ before ( :all ) do
119
+ class Forest < ActiveRecord ::Base
120
+ has_many :trees
121
+ end
122
+
123
+ class Tree < ActiveRecord ::Base
124
+ belongs_to :forest
125
+ end
126
+
127
+ class Fruit < ActiveRecord ::Base
128
+ belongs_to :tree
129
+ has_one :forest , through : :tree
130
+ end
131
+
132
+ ActiveRecord ::Base . establish_connection (
133
+ :adapter => 'sqlite3' ,
134
+ :database => @db_file
135
+ )
136
+ end
137
+
138
+ context 'revenue' do
139
+ it 'has an forest_id' do
140
+ expect ( Fruit . find ( 3 ) . respond_to? ( :forest_id ) ) . to be true
141
+ expect ( Fruit . find ( 3 ) . forest_id ) . to eq 1
142
+ expect ( Fruit . find ( 3 ) . forest . name ) . to eq "sherwood"
143
+ end
144
+
145
+ it 'has nil if tree id not available' do
146
+ expect ( Fruit . find ( 4 ) . respond_to? ( :tree_id ) ) . to be true
147
+ expect ( Fruit . find ( 4 ) . forest_id ) . to eq nil
148
+ end
149
+ end
150
+
151
+ # Clean up DB
152
+ after ( :all ) do
153
+ File . delete ( @db_file ) if File . exist? ( @db_file )
154
+ end
155
+ end
0 commit comments