Rails Arel 相当于这个复杂的 sql 查询



这是原始逻辑

(scrape_datas = ScrapeData.find(
  :all, :conditions => 
  "artist_status = 'NOT_FOUND' 
   AND blacklisted = 1 
   AND extracted = 0 
   and not EXISTS(
     SELECT * FROM artist_name_suggestions where original = artist_name
   )

我已经能够更好地拆分第一部分

scrape_datas = ScrapeData.where(
  :artist_status => 'NOT_FOUND',
  :blacklisted   => 1,
  :extracted     => 0
)

尽管在将"并且不存在"查询放入组合中时遇到问题

and not EXISTS(
  SELECT * FROM artist_name_suggestions where original = artist_name
)

谢谢!

首先,您可以提取简单的作用域:

scope :not_found, where(:artist_status => 'NOT_FOUND')
scope :blacklisted, where(:blacklisted => 1)
scope :extracted, where(:extracted => 0)

然后添加一个查询方法(假设artist_name是一列scrape_datas):

def self.no_suggestions
  scrape_datas = ScrapeData.arel_table
  suggestions = ArtistNameSuggestion.arel_table
  where(ArtistNameSuggestion.where(
    suggestions[:original].eq(scrape_datas[:artist_name])
  ).exists.not)
end

现在你可以做这样的事情:

ScrapeData.not_found.blacklisted.extracted.no_suggestions

相关内容

  • 没有找到相关文章

最新更新