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
当我搜索时出现以下错误:
When I search I get the following error:
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方法会自动进行连接。
What am I doing wrong?, I thought the includes method would make the join automatically.
推荐答案
来自文档:
使用
其中
仅当您将其传递给Hash时才起作用。对于
SQL片段,您需要使用引用
强制联接表
Using
where
like this will only work when you pass it a Hash. For SQL-fragments you need usereferences
to force joined tables
您是正确的, includes
方法将自动进行联接,但是当将散列用作<$ c $的参数时,仅 c>其中。
You are correct that the includes
method will make the join automatically, but only when a hash is used as the argument to where
.
这将检测查询并加入评论
:
Article.includes(:comments).where(comments: { visible: true })
这需要明确的引用
:
Article.includes(:comments).where("comments.visible = true").references(:comments)
不用担心 default_scope
是否是件好事,您可以使用以下代码运行代码:
Without getting into whether default_scope
is a good thing or not, you could get your code running with this:
def self.search(query)
if query
references(:artists).
where("title LIKE :query OR artists.name LIKE :query", query: "%#{query}%")
else
where nil
end
end
这篇关于Rails 4中的“ includes”方法似乎不适用于“ where”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!