新手问题 Rails 4 只有一条记录不能 all 也不能 each

syutran · April 10, 2015 · Last by dandananddada replied at April 13, 2015 · 1471 hits

如果表里没有记录,使用 all(controller)和 each(viewer)是报错的。该怎么办呢? 如果表里只有一条记录,也不能使用 all 和 each 的。又该怎么办呢? 肯定是我还没学到......

不会的,Model.all 会返回 []

应该是你那里姿势没对,但是有一个可以无损转换为 Array 的办法:

Array(any_object)

try catch 一下 def index begin @articles = Admin::Article.all rescue Exception => e #... else render json: @articles end end

You need to Sign in before reply, if you don't have an account, please Sign up first.