Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails:列出与给定ID集不匹配的记录_Ruby On Rails_Ruby_Ruby On Rails 3_Ruby On Rails 4_Ruby On Rails 5 - Fatal编程技术网

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)