回答編集履歴

2

---

2015/03/18 23:05

投稿

hello-world
hello-world

スコア1342

test CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- ----
5
+ ---
6
6
 
7
7
 
8
8
 

1

大幅な追記

2015/03/18 23:05

投稿

hello-world
hello-world

スコア1342

test CHANGED
@@ -1 +1,89 @@
1
1
  `update_all`は更新したデータの行数を返すため、`checked_item`がFixnumになっています。
2
+
3
+
4
+
5
+ ----
6
+
7
+
8
+
9
+ 追記:
10
+
11
+
12
+
13
+ 些事ですが
14
+
15
+ - データ数がゼロなら、`each`で回しても問題ありません。
16
+
17
+ - データが多くなることを考えると、`each`より`find_each`を使う方がよいです。
18
+
19
+ - 複数のデータを変更するばあいは、`transaction`で囲った方がよいでしょう。
20
+
21
+
22
+
23
+ ですので
24
+
25
+ ```lang-ruby
26
+
27
+ # before
28
+
29
+ unless no_check_item.count == 0
30
+
31
+ no_check_item.each do |item|
32
+
33
+ Navi.create(exhibitor: item.user_id, item_id: item.id, status: 1)
34
+
35
+ item.update({limit_check: true})
36
+
37
+ end
38
+
39
+ end
40
+
41
+ ```
42
+
43
+ は、
44
+
45
+ ```lang-ruby
46
+
47
+ #after
48
+
49
+ Item.transaction do
50
+
51
+ no_check_item.find_each do |item|
52
+
53
+ Navi.create(exhibitor: item.user_id, item_id: item.id, status: 1)
54
+
55
+ item.update(limit_check: true)
56
+
57
+ end
58
+
59
+ end
60
+
61
+ ```
62
+
63
+ とするのがよいでしょう。
64
+
65
+
66
+
67
+ また、これ以降`no_checked_item`のインスタンスには触れない(※)のであれば最初のように`update_all`を使ってもよいと思います。
68
+
69
+ ※)`update_all`はデータベースを直接変更するので、Railsから見える`no_check_item`の中身はチェックされていない状態が続きます。チェックされた状態のインスタンスが必要であればリロードする必要があります。
70
+
71
+ ```lang-ruby
72
+
73
+ Item.transaction do
74
+
75
+ no_check_item.find_each do |item|
76
+
77
+ Navi.create(exhibitor: item.user_id, item_id: item.id, status: 1)
78
+
79
+ end
80
+
81
+ no_check_item.update_all(limit_check: true) # 戻り値は読まなくてOK
82
+
83
+ end
84
+
85
+ ```
86
+
87
+
88
+
89
+ ループ中の`create`のパフォーマンスも気になるようであれば、`activerecord-import`というgemを利用するのがよいでしょう。