質問編集履歴

4

修正

2019/08/23 06:36

投稿

thesnowman
thesnowman

スコア154

test CHANGED
File without changes
test CHANGED
@@ -58,7 +58,7 @@
58
58
 
59
59
  ```
60
60
 
61
- は、@blog.images.first.pictureがarrayオブジェクトだからurlメソッドが使えないと出ました。
61
+ 今度は、@blog.images.first.pictureがarrayオブジェクトだからurlメソッドが使えないと出ました。
62
62
 
63
63
 
64
64
 

3

修正

2019/08/23 06:36

投稿

thesnowman
thesnowman

スコア154

test CHANGED
File without changes
test CHANGED
@@ -46,7 +46,7 @@
46
46
 
47
47
  しかし、これだとそもそも
48
48
 
49
- Blog.first.imagesが、ActiveRecord::Associations::CollectionProxyというオブジェクトらしくて、.picture.urlが機能しません。
49
+ @blog.imagesが、ActiveRecord::Associations::CollectionProxyというオブジェクトらしくて、.picture.urlが機能しません。
50
50
 
51
51
 
52
52
 

2

修正

2019/08/23 06:35

投稿

thesnowman
thesnowman

スコア154

test CHANGED
File without changes
test CHANGED
@@ -119,3 +119,41 @@
119
119
  コード
120
120
 
121
121
  ```
122
+
123
+ ---
124
+
125
+ Blogモデル
126
+
127
+ ```ruby
128
+
129
+ class Blog < ApplicationRecord
130
+
131
+ has_many :images, dependent: :destroy
132
+
133
+ accepts_nested_attributes_for :images
134
+
135
+
136
+
137
+ is_impressionable counter_cache: true
138
+
139
+ end
140
+
141
+ ```
142
+
143
+
144
+
145
+ Imageモデル
146
+
147
+ ```ruby
148
+
149
+ class Image < ApplicationRecord
150
+
151
+ belongs_to :blog, optional: true
152
+
153
+ mount_uploaders :picture, PictureUploader
154
+
155
+ end
156
+
157
+
158
+
159
+ ```

1

修正

2019/08/22 17:33

投稿

thesnowman
thesnowman

スコア154

test CHANGED
File without changes
test CHANGED
@@ -69,3 +69,53 @@
69
69
  聞きたいことをまとめると、Blogモデルのオブジェクトから関連付けているImageモデルの画像URLを取得したい。
70
70
 
71
71
  というものです。よろしくお願いいたします。
72
+
73
+
74
+
75
+ ---
76
+
77
+ migrationファイルだと長くなるので、schema.rbを載せます。
78
+
79
+ blogsのほうにもpictureカラムがありますが気にしないでください。
80
+
81
+ ```ruby
82
+
83
+ create_table "blogs", force: :cascade do |t|
84
+
85
+ t.integer "user_id"
86
+
87
+ t.text "content"
88
+
89
+ t.text "title"
90
+
91
+ t.text "category"
92
+
93
+ t.datetime "created_at", null: false
94
+
95
+ t.datetime "updated_at", null: false
96
+
97
+ t.string "picture"
98
+
99
+ t.integer "impressions_count", default: 0
100
+
101
+ end
102
+
103
+
104
+
105
+ create_table "images", force: :cascade do |t|
106
+
107
+ t.integer "blog_id"
108
+
109
+ t.string "picture"
110
+
111
+ t.datetime "created_at", null: false
112
+
113
+ t.datetime "updated_at", null: false
114
+
115
+ t.text "pictures"
116
+
117
+ end
118
+
119
+ コード
120
+
121
+ ```