![](/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.