質問編集履歴

2

index.html.erb及びコントローラーの編集。

2022/01/24 09:06

投稿

退会済みユーザー
test CHANGED
File without changes
test CHANGED
@@ -51,12 +51,18 @@
51
51
  コントローラー
52
52
  ```rb
53
53
  class ItemsController < ApplicationController
54
+ def new
54
- <----略---->>
55
+ @item = Item.new
56
+ end
57
+
58
+ def show
59
+ @item = Item.find(params[:id])
60
+ end
61
+
55
62
  def index
56
63
  @items = Item.all
57
64
  @ItemsAllSum = Item.all.sum(:price)
58
65
  end
59
- # winterboum様はindex内で記述するように回答頂いてますが、一旦後述のmonthメソッドで記述してます。
60
66
 
61
67
  def create
62
68
  @item = Item.new(item_params)
@@ -68,21 +74,29 @@
68
74
  render 'new'
69
75
  end
70
76
  end
77
+
71
- <<----略---->>
78
+ def destroy
72
- <<----以下該当メソッド---->>
79
+ @item = Item.find(params[:id])
80
+ @item.destroy
81
+ redirect_to '/items/index'
82
+ end
83
+
73
84
  def search_date
74
- @item = Item.find_by(params[:id]) # @itemにItemインスタンスを格納
75
- if !@item.nil? #インスタンスが存在していれば、
85
+ search_date = Time.new(2022, 1, 1)
86
+ end
87
+
88
+ def month
76
- @search_date = @item.buy_month # インスタンスの登録年月日を@search_dateに格納
89
+ month = Item.where(buy_month: search_date.beginning_of_month..search_date.end_of_month)
90
+ end
91
+
92
+ helper_method :search_date, :month
93
+ private
94
+
95
+ def item_params
96
+ params.require(:item).permit(:name, :price, :buy_month)
77
97
  end
78
98
  end
79
-
80
- def month
81
- @month = Item.where(created_at:
99
+ # 編集しました。(2022/1/24)
82
- @search_date.beginning_of_month..@search_date.end_of_month)
83
- end
84
-
85
- <<----略---->>
86
100
  ```
87
101
  一覧ページ
88
102
  ```rb
@@ -95,10 +109,17 @@
95
109
  <% end %>
96
110
  </ul>
97
111
 
98
- <<----略---->>
112
+ <div class=“index”>
113
+ <p>君の物欲合計金額は...<%= @ItemsAllSum %>円</p>
114
+ <p><%= link_to "まだ何か欲しいの?", '/' %><p>
115
+ </div>
99
116
 
117
+
118
+ <%= "1月に買うものは..." %>
119
+ <% month.each do |month| %>
120
+ <%= "#{month.name}" %>
100
- <%= search_date %>
121
+ <% end %>
101
- <%= month.name %> # ここでコントローラー内で前述ているmonthメソッドのnameを一旦試験的に呼び出ます
122
+ # 編集(2022/1/24)
102
123
  ```
103
124
  しかし<%= month.name %>の結果は 「Item」とだけ返ってきます。
104
125
  ここではnewフォームで登録している欲しいものの名前が返ってくることを期待しておりました。
@@ -111,3 +132,5 @@
111
132
 
112
133
 
113
134
 
135
+
136
+

1

monthメソッドを追加

2022/01/20 11:30

投稿

退会済みユーザー
test CHANGED
@@ -1 +1 @@
1
- Ruby on Rails 登録した年月日を取得、変数に格納し、ビューに描画させたい
1
+ Ruby on Rails 登録した年月日を取得し、ビューに描画させたい
test CHANGED
@@ -76,6 +76,12 @@
76
76
  @search_date = @item.buy_month # インスタンスの登録年月日を@search_dateに格納
77
77
  end
78
78
  end
79
+
80
+ def month
81
+ @month = Item.where(created_at:
82
+ @search_date.beginning_of_month..@search_date.end_of_month)
83
+ end
84
+
79
85
  <<----略---->>
80
86
  ```
81
87
  一覧ページ