簡體   English   中英

Rails 4中的“ includes”方法似乎不適用於“ where”

[英]'includes' method doesn't seem to work with 'where' in Rails 4

在我的模型中,我有:

class Song < ActiveRecord::Base

  belongs_to :artist

  def self.default_scope
    includes :artist
  end

  def self.search query
    if query
      where "title LIKE :query OR artists.name LIKE :query", query: "%#{ query }%"
    else
      where nil
    end
  end

end

在我的控制器中:

def index
  @songs = Song.search(params[:search])
  respond_with(@songs)
end

當我搜索時,出現以下錯誤:

Mysql2::Error: Unknown column 'artists.name' in 'where clause': SELECT  `songs`.* FROM `songs` WHERE (title LIKE '%my search%' OR artists.name LIKE '%my search%' OR albums.name LIKE '%my search%')

我在做什么錯?,我認為include方法會自動進行聯接。

文檔

僅當您將其傳遞給Hash時,才可以where這樣的where使用它。 對於SQL片段,您需要使用references來強制聯接表

您是正確的, includes方法將自動進行聯接,但當使用哈希作為where的參數時才可以進行聯接。

這將檢測查詢並加入comments

Article.includes(:comments).where(comments: { visible: true })

這需要顯式references

Article.includes(:comments).where("comments.visible = true").references(:comments)

無需研究default_scope是否是一件好事,就可以使用以下代碼運行代碼:

def self.search(query)
  if query
    references(:artists).
      where("title LIKE :query OR artists.name LIKE :query", query: "%#{query}%")
  else
    where nil
  end
end

includes不會生成join sql,因此您無法訪問其他表列。 實際上,這是一個非常棘手的方法,通常最好使用preloadjoins -了解差異將對您的應用程序性能產生巨大影響。 您需要在此處使用join

class Song < ActiveRecord::Base

  belongs_to :artist

  default_scope { joins :artist }

  def self.search query
    if query
      where "title LIKE :query OR artists.name LIKE :query", query: "%#{ query }%"
    else
      all
    end
  end
end

但是請注意,使用default_scope進行聯接或包含不是最干凈的方法,最終會因性能下降而對您產生反作用(以艱難的方式來學習)。

暫無
暫無

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

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