![](/img/trans.png)
[英]'includes' method doesn't seem to work with 'where' in Rails 4
[英]Rails : includes doesn't work in model scope
我在我的book
model 中创建了 scope 并希望包括author
关系。 不幸的是,该关系没有加载以下代码:
scope :search, ->(title) {
quoted_title = ActiveRecord::Base.connection.quote_string(title)
includes(:author).where("title % :title", title: title).
order(Arel.sql("similarity(title, '#{quoted_title}') DESC"))
}
我尝试了一些调整,例如使用 joins(:author).merge() 但关系仍未加载。 知道如何在 scope 中加载关系吗? 谢谢。
这里是 controller 用我通过 Ajax 调用的方法来渲染搜索结果:
def search
results_books = Book.search(search_params[:q]).first(5)
results_authors = Author.search(search_params[:q]).first(5)
results = results_books + results_authors
render json: { results: results }, status: :ok
end
对于 scope 中的搜索 function,如果我理解正确,您正在尝试根据标题字段挑选与搜索参数匹配的书籍。 如果是这样,我可以建议像这样的较短版本:
scope :search, lambda { |title|
where('title like ?', "%#{title}%")
}
至于将相关作者纳入json output。 我们通常在将 JSON 对象返回到前端时使用 JBuilder。 如果您坚持使用基本的 RoR,请查看 Substanstial https://stackoverflow.com/a/26800097/9972821的答案
这没有经过测试,所以让我知道它有多好。 我分享的帖子中的 rest 也提到了 JBuilder 作为首选替代方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.