質問編集履歴

2

追記

2017/12/07 10:35

投稿

shun4shun3
shun4shun3

スコア12

test CHANGED
File without changes
test CHANGED
@@ -75,3 +75,83 @@
75
75
 
76
76
 
77
77
  ```
78
+
79
+
80
+
81
+ 追記:
82
+
83
+ shishou == followerと変えました.
84
+
85
+
86
+
87
+ 以下のように書き,
88
+
89
+ project.owner
90
+
91
+ project.shishous
92
+
93
+ user.project_as_owner
94
+
95
+
96
+
97
+ はコンソールでセット,取得できるようになったのですが,
98
+
99
+ project.shishous << user1
100
+
101
+ と入れた時,
102
+
103
+ user1.projects_as_shishou が表示されないようです.
104
+
105
+
106
+
107
+
108
+
109
+ ```ruby
110
+
111
+ class Project < ApplicationRecord
112
+
113
+
114
+
115
+ has_many :project_shishous
116
+
117
+ has_many :shishous, through: :project_shishous, source: 'shishou'
118
+
119
+
120
+
121
+ belongs_to :owner, class_name: "User", foreign_key: "owner_id"
122
+
123
+
124
+
125
+ end
126
+
127
+
128
+
129
+ class User < ApplicationRecord
130
+
131
+ has_many :project_shishous
132
+
133
+ has_many :projects_as_shishou, through: :project_shishous, source: 'project'
134
+
135
+
136
+
137
+ has_many :projects_as_owner, class_name: 'Project', foreign_key: 'owner_id'
138
+
139
+ end
140
+
141
+
142
+
143
+ class ProjectShishou < ApplicationRecord
144
+
145
+ belongs_to :shishou, class_name: 'User', foreign_key: 'shishou_id'
146
+
147
+ belongs_to :project
148
+
149
+ end
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+ ```

1

修正

2017/12/07 10:35

投稿

shun4shun3
shun4shun3

スコア12

test CHANGED
File without changes
test CHANGED
@@ -1,6 +1,10 @@
1
1
  Rails で,モデルの設定に悩んでいます.
2
2
 
3
3
  以下のようなことを実現したいのですが,うまくいかないため,Model, Migrationファイルに何を書けばいいのか教えていただきたいです.
4
+
5
+
6
+
7
+ 以下のモデルが実現したいものです.
4
8
 
5
9
 
6
10
 
@@ -8,27 +12,47 @@
8
12
 
9
13
 
10
14
 
11
- # models
15
+ # model
12
16
 
13
- class User
17
+ # 中間テーブル
14
18
 
15
- has_many :projects, # as owner
19
+ class ProjectUser < ApplicationRecord
16
20
 
21
+ belongs_to :user
22
+
17
- belongs_to :project # as follower
23
+ belongs_to :project
18
24
 
19
25
  end
20
26
 
21
27
 
22
28
 
23
- class Project
29
+ class User < ApplicationRecord
24
30
 
25
- belongs_to :owner, class_name: 'User'
26
31
 
32
+
33
+ has_many :project_users
34
+
27
- has_many :followers, class_name: 'User'
35
+ # has_many :projects, through: :project_users
36
+
37
+ has_many :project_as_owner
38
+
39
+ has_many :project_as_follwer
28
40
 
29
41
  end
30
42
 
43
+
44
+
31
-
45
+ class Project < ApplicationRecord
46
+
47
+ has_many :project_users
48
+
49
+ # has_many :users, through: :project_users
50
+
51
+ has_many :follower, class_name: 'User'
52
+
53
+ has_one :owner, class_name: 'User'
54
+
55
+ end
32
56
 
33
57
 
34
58
 
@@ -40,7 +64,9 @@
40
64
 
41
65
  # result
42
66
 
43
- user.projects # as owner
67
+ user.projects_as_owner
68
+
69
+ user.project_as_follower
44
70
 
45
71
  project.owner
46
72