我正在尝试从数据库收集信息,然后通过闪存将该信息传递到我的 View 。不幸的是,该信息采用 ActiveRecord::Relation 格式,而不是我可以读取的任何格式。
Controller 查询
@message = Message.where(:all).limit(4).order(id: :desc).only(:order,:where)
flash[:response] = @message
redirect_to (:back)
如果我做类似的事情
@message = Message.where(:all).limit(4).order(id: :desc).only(:order,:where)
flash[:response] = @message.first.mess
redirect_to (:back)
为了尝试获取困惑列中的第一个返回值,我收到未定义的方法错误。我一直在尝试找到一个教程,告诉我如何在查询运行后获取信息,但最近我在 Rail 的教程上运气不佳。我感谢你们能提供的任何帮助。完成此操作后,我将尝试在 View 端格式化 4 个不同的结果。
最佳答案
消息列表:
@messages = Message.order(id: :desc).limit(4)
此:only(:order,:where)
取消您的limit(4)
(为什么?)
@messages
现在是一个 activerecord 关联,不适合输出......所以,如果你有 4 条消息,你可以这样做:
if @messages.any? # maybe no messages come out
flash[:response] = @messages.map(&:mess).join('<br>') # add an html newline between them
end
redirect_to :back
关于mysql - Rails 数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470871/