teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

4

修正

2019/08/23 06:36

投稿

thesnowman
thesnowman

スコア154

title CHANGED
File without changes
body CHANGED
@@ -28,7 +28,7 @@
28
28
  ```ruby
29
29
  @blog.images.first.picture.url
30
30
  ```
31
- は、@blog.images.first.pictureがarrayオブジェクトだからurlメソッドが使えないと出ました。
31
+ 今度は、@blog.images.first.pictureがarrayオブジェクトだからurlメソッドが使えないと出ました。
32
32
 
33
33
  他にもいろいろやってるのですができずに混乱しています。
34
34
 

3

修正

2019/08/23 06:36

投稿

thesnowman
thesnowman

スコア154

title CHANGED
File without changes
body CHANGED
@@ -22,7 +22,7 @@
22
22
  ```
23
23
 
24
24
  しかし、これだとそもそも
25
- Blog.first.imagesが、ActiveRecord::Associations::CollectionProxyというオブジェクトらしくて、.picture.urlが機能しません。
25
+ @blog.imagesが、ActiveRecord::Associations::CollectionProxyというオブジェクトらしくて、.picture.urlが機能しません。
26
26
 
27
27
  次に以下を試しました。
28
28
  ```ruby

2

修正

2019/08/23 06:35

投稿

thesnowman
thesnowman

スコア154

title CHANGED
File without changes
body CHANGED
@@ -58,4 +58,23 @@
58
58
  t.text "pictures"
59
59
  end
60
60
  コード
61
+ ```
62
+ ---
63
+ Blogモデル
64
+ ```ruby
65
+ class Blog < ApplicationRecord
66
+ has_many :images, dependent: :destroy
67
+ accepts_nested_attributes_for :images
68
+
69
+ is_impressionable counter_cache: true
70
+ end
71
+ ```
72
+
73
+ Imageモデル
74
+ ```ruby
75
+ class Image < ApplicationRecord
76
+ belongs_to :blog, optional: true
77
+ mount_uploaders :picture, PictureUploader
78
+ end
79
+
61
80
  ```

1

修正

2019/08/22 17:33

投稿

thesnowman
thesnowman

スコア154

title CHANGED
File without changes
body CHANGED
@@ -33,4 +33,29 @@
33
33
  他にもいろいろやってるのですができずに混乱しています。
34
34
 
35
35
  聞きたいことをまとめると、Blogモデルのオブジェクトから関連付けているImageモデルの画像URLを取得したい。
36
- というものです。よろしくお願いいたします。
36
+ というものです。よろしくお願いいたします。
37
+
38
+ ---
39
+ migrationファイルだと長くなるので、schema.rbを載せます。
40
+ blogsのほうにもpictureカラムがありますが気にしないでください。
41
+ ```ruby
42
+ create_table "blogs", force: :cascade do |t|
43
+ t.integer "user_id"
44
+ t.text "content"
45
+ t.text "title"
46
+ t.text "category"
47
+ t.datetime "created_at", null: false
48
+ t.datetime "updated_at", null: false
49
+ t.string "picture"
50
+ t.integer "impressions_count", default: 0
51
+ end
52
+
53
+ create_table "images", force: :cascade do |t|
54
+ t.integer "blog_id"
55
+ t.string "picture"
56
+ t.datetime "created_at", null: false
57
+ t.datetime "updated_at", null: false
58
+ t.text "pictures"
59
+ end
60
+ コード
61
+ ```