Ruby on rails RubyonRails:列出与给定ID集不匹配的记录
因此,我有三种模型:Ruby on rails RubyonRails:列出与给定ID集不匹配的记录,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-5,Ruby On Rails,Ruby,Ruby On Rails 3,Ruby On Rails 4,Ruby On Rails 5,因此,我有三种模型: class Restaurant < ActiveRecord::Base has_many :reviews has_many :users, through: :reviews end class Review < ActiveRecord::Base belongs_to :restaurant belongs_to :user end class User < ActiveRecord::Base has_many :rev
class Restaurant < ActiveRecord::Base
has_many :reviews
has_many :users, through: :reviews
end
class Review < ActiveRecord::Base
belongs_to :restaurant
belongs_to :user
end
class User < ActiveRecord::Base
has_many :reviews
has_many :restaurants, through: :reviews
end
好的。但如果我想列出所有未经@user审核的餐厅,该怎么办?
我试过这个:
Restaurant.joins(:reviews).where.not(“reviews.user_id": @user.id)
不幸的是,这不起作用,因为它还将返回@user审核过的、其他用户审核过的餐厅
我想出了一个可怕而昂贵的方法:
Restaurant.joins(:reviews).reject {|x| x.users.where(id: @user.id).present? }
我相信一定有更好的办法。救命啊 这很容易
您必须映射@user审核的所有餐厅的ID
reviewed_restaurants = Restaurant.joins(:reviews).where("reviews.user_id": @user.id).map(&:id)
然后触发另一个查询以获取以前选择的餐馆以外的餐馆
@unreviewed_restaurants = Restaurant.where("id not in (?)", reviewed_restaurants)
希望对你有用
@unreviewed_restaurants = Restaurant.where("id not in (?)", reviewed_restaurants)