質問編集履歴

3

追記の修正

2019/10/22 12:41

投稿

nanase21
nanase21

スコア144

test CHANGED
File without changes
test CHANGED
@@ -81,3 +81,9 @@
81
81
 
82
82
 
83
83
  current_userは取れていて、リレーション関係になっているlikeまでのレコードも取れています。
84
+
85
+ ちなみにfind_byをwhereにしてpluck(:id)にするとidは取れます。
86
+
87
+ しかし、pluckでカラムを取得すると配列で値を受け取ってしまうのでwhere以外のfind_byで取ろうとしています。
88
+
89
+ 落ちる手前のview側でbinding.pryかけたターミナル上で.idまで取得出来るのですがview側で同じことをしようとすると落ちてしまいます。

2

追記の修正

2019/10/22 12:41

投稿

nanase21
nanase21

スコア144

test CHANGED
File without changes
test CHANGED
@@ -80,4 +80,4 @@
80
80
 
81
81
 
82
82
 
83
- # current_userは取れていて、リレーション関係になっているlikeまでのレコードも取れています。
83
+ current_userは取れていて、リレーション関係になっているlikeまでのレコードも取れています。

1

質問に対する追記

2019/10/22 12:39

投稿

nanase21
nanase21

スコア144

test CHANGED
File without changes
test CHANGED
@@ -21,3 +21,63 @@
21
21
  # 実現したいこと
22
22
 
23
23
  view側でもターミナル上で取れたようにidだけ取得出来るようにしたい。
24
+
25
+
26
+
27
+
28
+
29
+ ```ruby
30
+
31
+ # questions_controller
32
+
33
+ def show
34
+
35
+  @question = Question.find_by(id: params[:id])
36
+
37
+ end
38
+
39
+
40
+
41
+ # answer model
42
+
43
+ has_many :likes, class_name: 'Like', foreign_key: 'answer_id'
44
+
45
+ belongs_to :user, optional: true
46
+
47
+
48
+
49
+ def like(id, answer_id)
50
+
51
+ Like.find_by(user_id: id, answer_id: answer_id).status.to_i
52
+
53
+ end
54
+
55
+
56
+
57
+ # question model
58
+
59
+ belongs_to :user, optional: true
60
+
61
+ has_many :answers, class_name: 'Answer', foreign_key: 'question_id'
62
+
63
+
64
+
65
+ # user model
66
+
67
+ has_many :like, class_name: 'Like', foreign_key: 'answer_id'
68
+
69
+
70
+
71
+ # view
72
+
73
+ - @question.answers.each do |a|
74
+
75
+ = current_user.like.find_by(answer_id: a).id
76
+
77
+ # .idとすると落ちる
78
+
79
+ ```
80
+
81
+
82
+
83
+ # current_userは取れていて、リレーション関係になっているlikeまでのレコードも取れています。