質問編集履歴

2

追加

2018/05/27 09:34

投稿

ssk
ssk

スコア332

test CHANGED
File without changes
test CHANGED
@@ -17,6 +17,18 @@
17
17
  ```SQL
18
18
 
19
19
  SELECT "affiliations".* FROM "affiliations" INNER JOIN "branches" ON "affiliations"."id" = "branches"."affiliation_id" WHERE "affiliations"."deleted_at" IS NULL AND "branches"."order_id" = $1 LIMIT $2 [["order_id", 8161], ["LIMIT", 1]]
20
+
21
+ ```
22
+
23
+
24
+
25
+ ## 試してこと
26
+
27
+ このように中間テーブルから辿ると表示することができました。
28
+
29
+ ```ruby
30
+
31
+ <%= order.branch&.affiliation&.name %>
20
32
 
21
33
  ```
22
34
 

1

修正

2018/05/27 09:34

投稿

ssk
ssk

スコア332

test CHANGED
File without changes
test CHANGED
@@ -1,11 +1,65 @@
1
+ viewでaffiliationがnilになります。
2
+
3
+ リレーションの貼り方が間違っていますか?
4
+
5
+
6
+
7
+ ```ruby
8
+
9
+ # index.html.slim
10
+
11
+ <%= order.affiliation.name %>
12
+
13
+ ```
14
+
15
+ ## order.affiliationで発行されるSQL
16
+
17
+ ```SQL
18
+
19
+ SELECT "affiliations".* FROM "affiliations" INNER JOIN "branches" ON "affiliations"."id" = "branches"."affiliation_id" WHERE "affiliations"."deleted_at" IS NULL AND "branches"."order_id" = $1 LIMIT $2 [["order_id", 8161], ["LIMIT", 1]]
20
+
21
+ ```
22
+
23
+
24
+
25
+ # リレーション
26
+
1
27
  ```ruby
2
28
 
3
29
  class Order < ApplicationRecord
4
30
 
5
- has_one :responsible_branch_driver_backorder, dependent: :destroy
31
+ has_one :branch, dependent: :destroy
6
32
 
7
- has_one :affiliation, through: :responsible_branch_driver_backorder
33
+ has_one :affiliation, through: :branch
8
34
 
9
35
  end
10
36
 
11
37
  ```
38
+
39
+
40
+
41
+ ```ruby
42
+
43
+ class Branch < ApplicationRecord
44
+
45
+ belongs_to :order
46
+
47
+ belongs_to :affiliation
48
+
49
+ end
50
+
51
+ ```
52
+
53
+
54
+
55
+ ```ruby
56
+
57
+ class Affiliation < ApplicationRecord
58
+
59
+ has_many :branches, dependent: :destroy
60
+
61
+ has_many :orders, through: :branches
62
+
63
+ end
64
+
65
+ ```