Rails:获取属于具有特定枚举属性的类别的相关记录

时间:2017-03-17 12:03:58

标签: sql ruby-on-rails ruby postgresql activerecord

在我的rails应用中,我有 string = "<![CDATA[[[[[Lorem ipsum feed for an interval of 30 seconds]]]]]]]>" inner_str = string.split('[')[len(string.split('[')) -1 ].split(']')[0] print inner_str 以及属于Organizations的相关帖子。 Organization模型具有类型属性,即。枚举 例如:gov,:edu,:体育等。

Organization

我可以使用

获取edu类型的组织列表
enum sp_type: { gov: 0, edu: 1, sports: 2 }

我可以通过Organization.edu

获取帖子

我想获取属于sp_type Organization.edu.includes(:posts)组织的所有帖子,我应该执行哪些查询来获取按edu排序的所有帖子的列表。

1 个答案:

答案 0 :(得分:1)

  1. type用于STI,因此不建议将其用作列名。
  2. 查询(以获取组织):

    Organization.where(sp_type: Organization.sp_types[:edu]))
                .includes(:posts)
                .where.not(posts: { id: nil })
                .order('posts.updated_at')
    
  3. 获取帖子的查询:

    Post.joins(:organization)
        .where(organizations: { sp_type: Organization.sp_types[:edu]})
        .group('posts.id')
        .order('posts.updated_at')