簡體   English   中英

Rails 4 + ActiveRecord:如何從搜索中排除某些記錄?

[英]Rails 4 + ActiveRecord: How to exclude some records from the search?

我有這些表:

  1. users -經典的Devise表
  2. listings -用戶創建列表
  3. listings_exclude_users -2列: user_idlisting_id

user.rb

class User 
  has_many :listings
end 

listing.rb

class Listing
  belongs_to :user
  has_many :listing_excluded_users
end

listing_excluded_user.rb

class ListingExcludedUser
  belongs_to :user
  belongs_to :listing
end

我標記了一些用戶,這些用戶不應在相應的列表中可見,並且此信息保存在listings_exclude_users

現在,我想運行一個查詢,該查詢將獲取所有列表,但是如果針對特定列表listings_exclude_users了位於listings_exclude_users表中的用戶,則不要獲取該列表。

我可以在視圖中做到這一點,但我更喜歡ActiveRecord的方式。 我試過了

@listings = Listing.joins(:listing_excluded_users).where("listings.status='0' AND (listing_excluded_users.user_id != '#{current_user.id}')")

但是此查詢不返回任何內容(空@listings )。

預先感謝您的建議。

這可以很容易地在兩個查詢中完成。 如果需要一個查詢,則可能需要一個子查詢。

2個查詢:

user_ids_to_exclude = ListingExcludedUser.where.not(user_id: current_user.id).pluck(:user_id)
@listings = Listing.where.not(user_id: user_ids_to_exclude)

子查詢

@listings = Listing.where.not(user_id: ListingExcludedUser.where.not(user_id: current_user.id).select(:user_id))

注意:where.not是Rails 4慣用語。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM