Ruby on Rails:有没有办法从数据库中提取项目并按指定顺序返回它们?
我有一个项目ID, item_ids
。
我将此数组传递给ActiveRecord查询以从数据库中检索相应的项: Item.where(:id => item_ids)
有没有办法以与通过item_ids
数组传入的顺序相同的顺序返回项目?
如果它有所不同,我在Ruby on Rails 3.0.12上使用PostgreSQL作为我的数据库。
您可以让数据库进行排序并避免多个index
调用,您只需记住表达式而不是列的SQL ORDER BY顺序:
whens = item_ids.collect.with_index { |id, i| "when #{id} then #{i}" }.join(' ') items = Item.where(:id => item_ids).order("case id #{whens} end")
- 预加载与动态条件的关联
- Rails ActiveRecord查询日期范围
- ActiveModel :: SecurePassword未定义方法`password_digest =’
- Rails中两个类之间的多个belongs_to关系
- Ruby on Rails:关于validates_presence_of的问题
- rails 3 / postgres – 如果不应用,则为字符串多长时间:模式中的限制
- Rails ActiveRecord:是否可以组合:include和:conditions查询?
- Rails has_many:通过“子对象”的sum属性 – > SQL Toughy
- ActiveRecord :: AssociationTypeMismatch:用户期望,得到了Fixnum