代码之家  ›  专栏  ›  技术社区  ›  anonn023432

Rails查找除已关联的第二级以外的所有记录

  •  0
  • anonn023432  · 技术社区  · 7 年前

    我的Rails应用程序中有以下模型

    模型 community :

    class Community < ActiveRecord::Base
      has_many :community_program
    end
    

    模型 community_program :

    class CommunityProgram < ActiveRecord::Base
      belongs_to :program_name
    end
    

    模型 program_name :

    class ProgramName < ActiveRecord::Base
      has_many :community_programs
    end
    

    我正试图找到一种方法 program_names 不属于 社区计划 已分配给 社区 .

    我已经把所有的 程序名称 然后移除 程序名称 它已经与 社区 但那很贵。我可以直接提取二级未关联记录吗?

    编辑:问题与链接问题不同,因为在本例中, 程序名 可能与其他社区的社区计划有关联,但如果该名称与当前社区没有关联,我们仍然希望包含该名称。 社区 .

    **编辑2:我想提取尚未分配给与特定社区关联的社区程序的所有程序名。它们可以与与不同社区关联的社区计划关联。用例是,用户应该能够从剩余名称列表中选择一个名称,并将其分配给与其社区关联的社区程序。

    项目名称是全局的,尽管特定社区的社区项目的项目名称是唯一的,但不同社区可以将社区项目与相同的项目名称关联起来**

    4 回复  |  直到 7 年前
        1
  •  1
  •   Pavel Mikhailyuk    7 年前

    except_community Community

    except_relation = except_community.
      community_programs.
      select(:program_name_id)
    
    ProgramName.
      where.not(id: except_relation)
    

        2
  •  1
  •   gasc    7 年前

    class Community < ActiveRecord::Base
      has_many :community_programs
    end
    
    class CommunityProgram < ActiveRecord::Base
      belongs_to :program_name, optional: true
      belongs_to :community
    end
    
    class ProgramName < ActiveRecord::Base
      has_many :community_programs
    end
    
    some_community            = Community.find some_community_id
    programs_from_a_community = some_community.community_programs.map &:id 
    program_names_to_exclude  = CommunityProgram.where(id: programs_from_a_community)
                                                .where.not(program_name_id: nil)
                                                .map { |c_p| c_p.program_name.id }
    program_names             = ProgramName.where.not(id: program_names_to_exclude)
    
        3
  •  0
  •   anonn023432    7 年前

    ProgramName.where.not(id: except_community.community_programs.pluck(:program_name_id))
    

        4
  •  -1
  •   Brittany Hicks    7 年前

    association

    has_many :unassigned_program_names, -> { where community_program_id: nil }
    

    scope

    scope :unassigned, -> { where(community_program_id: nil) }
    

    推荐文章