Rails查询具有多个嵌套属性

时间:2018-06-26 08:34:09

标签: ruby-on-rails nested rails-activerecord

我的Rails 5应用程序中有两个模型:

class Post < ApplicationRecord
  has_many :tags
end

class Tag < ApplicationRecord
  belongs_to :post
end

在我的数据库中,例如,我有两个帖子,每个帖子都有2个不同的标签。如何通过两个特定标签(tag.title =“ tagname1”和tag.title =“ tagname2”)搜索帖子:

Post.includes(:tags).where(tag: {title: "tagName1"}).where(tag: {title: 
"tagName2"})

谢谢

3 个答案:

答案 0 :(得分:1)

解决方案

Post.joins(:tags)
  .where(tags: { title: ['tag1', 'tag2'] })
  .group('posts.id')
  .having('count(tags.post_id) = ?', 2)

假设:

  • 您对每个帖子的tag.title都有唯一性验证,如下所示:

    class Tag < ApplicationRecord
      belongs_to :post
    
      validates :title, uniqueness: { scope: :post }
    end
    

    ...否则,上述解决方案将不起作用,因为:

    # it will still also match the following Post
    Post(id: 1)
      Tag(post_id: 1, title: 'tag1')
      Tag(post_id: 1, title: 'tag1')
    
    # but that you only want instead those like the following:
    Post(id: 2)
      Tag(post_id: 2, title: 'tag1')
      Tag(post_id: 2, title: 'tag2')
    

答案 1 :(得分:0)

通过两个特定标签搜索帖子

Post.includes(:tags).where("tags.title IN (?)",["tagName1", "tagName"]).references(:tag)

这将返回所有带有tag.title或“ tagName1”或“ tagName”的帖子

答案 2 :(得分:0)

您可以使用arel进行更简洁的查询。

 demo= FirebaseDatabase.getInstance().getReference().child("IDS").child("/News");


    demo.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
                RvClass rvClass = snapshot.getValue(RvClass.class);
                list.add(rvClass);

            }
            CustomAdapter adapter = new CustomAdapter(SubmitNews.this,list);
            rv.setAdapter(adapter);

        }


       @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });