我想获得一个给定一组id的ActiveRecord对象数组.
我认为
Object.find([5,2,3])
Run Code Online (Sandbox Code Playgroud)
将返回一个数组,其中包含对象5,对象2,然后按顺序返回对象3,但我得到的数组按对象2,对象3和对象5排序.
ActiveRecord Base 查找方法API提到您不应该按照提供的顺序期望它(其他文档不提供此警告).
一个可能的解决方案是按相同顺序的ID数组查找的?,但订单选项似乎对SQLite无效.
我可以编写一些ruby代码来自己对对象进行排序(有点简单,缩放比例较差或缩放比较复杂),但是有更好的方法吗?
在我的Rails 4应用程序中,我的目标是查看所有联系人,其中“ visible_to联系人”表中的字段等于1。“我visible_to是” :integer, array: true。
但是,出现以下异常:
PG::UndefinedFunction: ERROR: operator does not exist: integer[] = integer
LINE 1: ....* FROM "contacts" WHERE "contacts"."visible_to" IN (1) OR...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.: SELECT "contacts".* FROM "contacts" WHERE "contacts"."visible_to" IN (1) ORDER BY created_at DESC
我搜索了答案,据我所知存在一种类型的问题visible_to。但是,我找不到解决方案。我也试图从演员提示中受益,但徒劳无功。
我的迁移:
class AddVisibleToToContacts < ActiveRecord::Migration
def change
add_column :contacts, :visible_to, :integer, array: true, default: [], using: …Run Code Online (Sandbox Code Playgroud)