Rails查询,其中至少有1条关联记录包含一个属性

时间:2019-01-18 16:53:13

标签: ruby-on-rails

我有一个GroupMeetings表和一个GroupMeetingsUser表,该表是UserGroupMeetings之间的联接表。我想找到所有至少有1个GroupMeetingsUser具有属性的GroupMeetings。

现在,这可行:

   @group_meetings = GroupMeeting.where('lang_one_id IN (?) AND lang_two_id IN (?) AND meeting_time >= ?', @user.languages.pluck(:id), @user.languages.pluck(:id), Date.today)

   @new_group_meetings_id = []

   @group_meetings.each do |meeting|
     meeting.group_meetings_user.each do |user|
       if(user.user.location === @user.location)
         @new_group_meetings_id.push(meeting.id)
       end
     end
   end

   @group_meetings = GroupMeeting.where('id IN (?)', @new_group_meetings_id)

但是如何在原始GroupMeetings查询中包含.each循环呢?就像使用.joins(:group_meetings_user)来查找至少有一个用户具有属性的所有记录吗?

class GroupMeeting < ApplicationRecord
    has_many :group_meetings_users
    has_many :users, through: :group_meetings_users
end

class GroupMeetingsUser < ApplicationRecord
    belongs_to :user
    belongs_to :group_meeting

    validates_presence_of :user_id, :group_meeting_id
    validates :user_id, :uniqueness => {:scope => :group_meeting_id, :message => 'can only join each group once.'}
end

更新1:

GroupMeeting.joins(:users).where(group_meeting: { lang_one_id: @user.languages.pluck(:id), lang_two_id: @user.languages.pluck(:id), meeting_time: DateTime.now..DateTime::Infinity.new}, user: { location: @user.location })

给出错误:

no such column: group_meeting.lang_one_id: SELECT "group_meetings".* FROM "group_meetings" INNER JOIN "group_meetings_users" ON "group_meetings_users"."group_meeting_id" = "group_meetings"."id" INNER JOIN "users" ON "users"."id" = "group_meetings_users"."user_id" WHERE "group_meeting"."lang_one_id" IN (29, 30, 31, 22) AND "group_meeting"."lang_two_id" IN (29, 30, 31, 22) AND ("group_meeting"."meeting_time" >= ?) AND "user"."location" = ?

1 个答案:

答案 0 :(得分:0)

我建议以下内容:

GroupMeeting
  .joins('INNER JOIN languages l1 ON languages l1.id = group_meetings.lang_one_id')
  .joins('INNER JOIN languages l2 ON languages l2.id = group_meetings.lang_two_id')
  .joins(:group_meeting_users => :users)
  .where('meeting_time >= ?', Date.today)
  .select('group_meetings.*')
  .group('group_meetings.id')
  .having('users.location = ?', @user.location)

它应该比进行子选择(使用languages.id IN (?)pluck)更快

让我知道是否可行和/或您有任何疑问。