'includes'方法似乎不适用于Rails 4中的'where'

mar*_*ngf 1 activerecord ruby-on-rails ruby-on-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
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

def index
  @songs = Song.search(params[:search])
  respond_with(@songs)
end
Run Code Online (Sandbox Code Playgroud)

当我搜索时,我收到以下错误:

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%')
Run Code Online (Sandbox Code Playgroud)

我做错了什么?,我认为include方法会自动进行连接.

mes*_*jah 7

来自文档:

使用where这样的方法只有在你传递哈希时才有效.对于SQL片段,您需要使用references强制连接表

你是正确的,该includes方法将自动进行连接,但只有当哈希被用作参数时才是where.

这将检测查询并加入comments:

Article.includes(:comments).where(comments: { visible: true })
Run Code Online (Sandbox Code Playgroud)

这需要明确references:

Article.includes(:comments).where("comments.visible = true").references(:comments)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)