Ruby on rails “includes”方法似乎不适用于Rails 4中的“where”
在我的模型中,我有:Ruby on rails “includes”方法似乎不适用于Rails 4中的“where”,ruby-on-rails,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,在我的模型中,我有: 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
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
当我搜索时,我得到以下错误:
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%')
我做错了什么?我以为includes方法会自动进行联接。includes不会生成联接sql,因此您无法访问其他表列。事实上,这是一种非常棘手的方法,通常最好使用预加载或连接-了解差异将对应用程序性能产生巨大影响。您需要在此处使用“加入”:
但是请注意,对联接或包含使用default_作用域并不是最干净的方法,最终会适得其反,因为您已经了解到,这是一种会带来性能惩罚的艰难方法 includes不会生成联接sql,因此您无法访问其他表列。事实上,这是一种非常棘手的方法,通常最好使用预加载或连接-了解差异将对应用程序性能产生巨大影响。您需要在此处使用“加入”:
但是请注意,对联接或包含使用default_作用域并不是最干净的方法,最终会适得其反,因为您已经了解到,这是一种会带来性能惩罚的艰难方法 来自:
像这样使用where只能在传递散列时起作用。对于
您需要的SQL片段使用引用来强制联接表
正确的说法是,includes方法将自动进行连接,但仅当hash用作where的参数时
这将检测查询并加入注释:
这需要明确的参考:
不必讨论默认的_范围是否是一件好事,您可以通过以下方式运行代码:
def self.search(query)
if query
references(:artists).
where("title LIKE :query OR artists.name LIKE :query", query: "%#{query}%")
else
where nil
end
end
从:
像这样使用where只能在传递散列时起作用。对于
您需要的SQL片段使用引用来强制联接表
正确的说法是,includes方法将自动进行连接,但仅当hash用作where的参数时
这将检测查询并加入注释:
这需要明确的参考:
不必讨论默认的_范围是否是一件好事,您可以通过以下方式运行代码:
def self.search(query)
if query
references(:artists).
where("title LIKE :query OR artists.name LIKE :query", query: "%#{query}%")
else
where nil
end
end
当我在php中实现类似于includes的东西时,我可以看到这样做的消耗程度,特别是includes单独运行每个请求。当我在php中实现类似于includes的东西时,我可以看到这样做的消耗程度,特别是包括单独运行每个请求
Article.includes(:comments).where(comments: { visible: true })
Article.includes(:comments).where("comments.visible = true").references(:comments)
def self.search(query)
if query
references(:artists).
where("title LIKE :query OR artists.name LIKE :query", query: "%#{query}%")
else
where nil
end
end