我有以下 STI 设置:
class Cage < ActiveRecord::Base
has_many :animals
end
class Animal < ActiveRecord::Base
belongs_to :cage
end
class Cat < Animal
# name = "Tom"
end
class Mouse < Animal
# name = "Jerry"
end
我想在返回以下结构的 Animals 表上进行选择:
+----+-----------------------+
| ID | cat_name | mouse_name |
+----+-----------------------+
| 1 | Tom | Jerry |
+----+-----------------------+
理想情况下,我想要这样的东西:
Cage \
.joins(:animals)
.select("
cages.id,
animals.name as case animals.type
when 'Mouse' then mouse_name
when 'Cat' then cat_name end
") \
.group('cages.id')
但这不起作用,所以我这样做了:
Cage \
.joins(:animals)
.select("
cages.id,
case animals.type when 'Mouse' then animals.name end mouse_name end,
case animals.type when 'Cat' then animals.name cat_name end
") \
.group('cages.id')
有没有办法使第一个查询工作,如果没有,是否有更好/替代的方法来编写第二个查询?