转换选择和收集方法为连接 [英] convert select and collect methods into joins
问题描述
我学习联接我有三个型号
I am learning joins I have three models
class Booking < ActiveRecord::Base
has_and_belongs_to_many :groups
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
belongs_to :group
has_and_belongs_to_many :bookings
end
class Group < ActiveRecord::Base
has_many :users
has_and_belongs_to_many :bookings
end
booking = Booking.first
booking.groups.collect{|g| g.users.select{|u| !self.users.include? u}}.flatten
我想这是不是在预订团体预订的所有用户提供一些这样的事
I want to get all users which are not booked in booking groups some thing like this
booking=Booking.first
booking.groups.collect{|g| g.users.select{|u| !self.users.include? u}}.flatten
我
如何才能做到这一点的联接,而不是收集和选择?
How can I do it with joins instead collect and select?
推荐答案
这应该是这样的(使用的 AREL 宝石):
It should be something like (using arel gem):
class User < ActiveRecord::Base
scope :non_booked_for, ->(booking_id) {
users = User.arel_table
bookings = Booking.arel_table
groups = Group.arel_table
where(groups_bookings[:booking_id].eq(booking_id)
.and(groups_bookings[:group_id].eq(users[:group_id])))
.not.where(user_bookings[:user_id].eq(users[:id])
.and(user_bookings[:booking_id].eq(booking_id)))
end
end
用法:
users = User.non_booked_for Booking.first.id
它只是使用否定所有的用户,这属于组和预订,其组所属的预订了。但我不肯定的否定将正常工作在这里,所以应该进行调试。并请在这两个表名称: users_bookings
或 bookings_users
的关联,因此,例如,模型会导致:
It just uses negation to all users, which belong to group and bookings, and its group belongs to that booking too. But I'm not sure that the negation will work properly here, so it should be debugged. And please select on of the two table names: users_bookings
, or bookings_users
for the associations, so, for example, in models it will lead to:
has_and_belongs_to_many :users
has_and_belongs_to_many :bookings, table_name: :users_bookings
这篇关于转换选择和收集方法为连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!