当我尝试做一个香草find_each
时,它会一直返回nil
,即使有应该作用的对象/记录。
[28] pry(main)> Node.find_each do |node|
[28] pry(main)* end
Node Load (1.0ms) SELECT "nodes".* FROM "nodes" ORDER BY "nodes"."id" ASC LIMIT 1000
=> nil
[29] pry(main)> Node.all.find_each do |node|
[29] pry(main)* node
[29] pry(main)* end
Node Load (0.7ms) SELECT "nodes".* FROM "nodes" ORDER BY "nodes"."id" ASC LIMIT 1000
=> nil
[31] pry(main)> Node.count
(0.5ms) SELECT COUNT(*) FROM "nodes"
=> 2
[32] pry(main)> Node.find_each do |node|
[32] pry(main)* puts node
[32] pry(main)* end
Node Load (0.5ms) SELECT "nodes".* FROM "nodes" ORDER BY "nodes"."id" ASC LIMIT 1000
#<Node:0x007fd49ffbc680>
#<Node:0x007fd49ffbc388>
=> nil
如何让find_each
简单地输出该模型的所有对象,就像Node.all
那样,为什么它只输出看似每个节点的AR对象的ID,只有当我做了puts node
?
[35] pry(main)> Node.all
Node Load (0.4ms) SELECT "nodes".* FROM "nodes"
=> [#<Node id: 85, name: "House Fire 2", family_tree_id: 57, user_id: 57, media_id: 228, media_type: "Video", created_at: "2015-05-15 00:20:26", updated_at: "2015-05-20 01:06:34", circa: nil, is_comment: nil, cached_votes_total: 0, cached_votes_score: 0, cached_votes_up: 0, cached_votes_down: 0, cached_weighted_score: 0, cached_weighted_total: 0, cached_weighted_average: 0.0>,
#<Node id: 86, name: "10PP Form Video", family_tree_id: 57, user_id: 57, media_id: 229, media_type: "Video", created_at: "2015-05-15 01:26:28", updated_at: "2015-05-22 20:35:58", circa: nil, is_comment: nil, cached_votes_total: 1, cached_votes_score: 1, cached_votes_up: 1, cached_votes_down: 0, cached_weighted_score: 1, cached_weighted_total: 1, cached_weighted_average: 0.0>]
答案 0 :(得分:4)
> Node.find_each do |node|
> end
=> nil
在这种情况下,nil来自该块的定义;不是Node.find_each
的结果。
尝试按如下方式在块中打印出来:
> Node.find_each do |node|
> puts node.id
> end
这将打印出2个ID。
打印出所有对象:
> Node.find_each do |node|
> puts node.inspect
> end