@putts = @putts + content.putt
は
ruby
1@putts += content.putt
のようにも書けますし、初期化も多重代入を使うと
@putts, @score, @par, @ob, @water = 0, 0, 0, 0, 0
のように書けるので、それらを使うと下のように少しスッキリ書くことができます。
ruby
1def edit
2 @game = Game.find(params[:id])
3 @contents = Content.where(game_id:params[:id])
4 @putts, @score, @par, @ob, @water = 0, 0, 0, 0, 0
5
6 @contents.each do |content|
7 @putts += content.putt
8 @score += content.score
9 @par += content.par
10 @ob += content.ob
11 @water += content.water
12 end
13end
さらに、reduce
(inject
)を使うと、ここでは初期化も不要なので以下のように書くこともできます。
ruby
1def edit
2 @game = Game.find(params[:id])
3 @contents = Content.where(game_id:params[:id])
4
5 @putts = @contents.map(&:putt).reduce(&:+)
6 @score = @contents.map(&:score).reduce(&:+)
7 @par = @contents.map(&:par).reduce(&:+)
8 @ob = @contents.map(&:ob).reduce(&:+)
9 @water = @contents.map(&:water).reduce(&:+)
10end
しかしここでは、ActiveRecordのsum
を使うのが一番スッキリするでしょう。
ruby
1def edit
2 @game = Game.find(params[:id])
3 @contents = Content.where(game_id:params[:id])
4
5 @putts = @contents.sum(:putt)
6 @score = @contents.sum(:score)
7 @par = @contents.sum(:par)
8 @ob = @contents.sum(:ob)
9 @water = @contents.sum(:water)
10end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/10/15 14:35