2016-08-19 58 views
0

我目前正在使用一个rails应用程序,他有一个本地API,我通过ajax请求从我的主模型Book.rb获取搜索功能的数据。如何在SQL查询中调用另一个模型的关联属性?

我希望能够在Book.rb SQL查询中包含Category.rb属性。

db结构是这样的。

class Book < ActiveRecord::Base 
    has_many :book_category_relations 
    has_many :categories, through: :book_category_relations 
end 

class BookCategoryRelation < ActiveRecord::Base 
    belongs_to :book 
    belongs_to :category 
end 

class Category < ActiveRecord::Base 
    has_many :books, through: :book_category_relations 
    has_many :book_category_relations 
end 

这里是我在这个时候在我的book.rb上执行的查询。

Book.rb 
    scope :search, -> query { where("lower(title) LIKE ? OR lower(author) LIKE ? OR lower(publisher) LIKE ? OR lower(publication_year) LIKE ? OR lower(country_of_origin) LIKE ? OR lower(description) LIKE ? OR lower(category) LIKE ?", 
     "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase) } 
end 

这就是我的.json.jbuilder的样子。

app/views/api/books/index.json.jbuilder 

json.array! @books do |book| 
    json.title book.title 
    json.author book.author 
    json.publisher book.publisher 
    json.image_url book.cover.url 
    json.id book.id 
    json.publication_year book.publication_year 
    json.country_of_origin book.country_of_origin 
    json.description book.description 
    json.price book.price 
    if book.categories[0] != nil 
    json.category book.categories[0].name 
    end 
end 

我希望能够以包括Book.categories.name到我的书模型中定义,所以我可以与我的书型号类别搜索范围。

我试着: 1.下(book.categories) 2.低级(book.category.name)

这是通过http://localhost:3000/api/books/?utf8=%E2%9C%93&search=diccionario

[ 
{ 
title: "DICCIONARIO DEL ESPAÑOL JURIDICO", 
author: "Santiago Muñoz Machado", 
publisher: "Consejo General del Poder Judicial", 
image_url:  "/system/books/covers/000/", 
id: 30, 
publication_year: "2016", 
country_of_origin: "España", 
description: null, 
price: "175.0", 
category: [ 
    { 
    name: "Diccionarios" 
    } 
    ] 
} 
] 

任何的API的图提示,提示或参考表示赞赏!

回答

0
scope :search, -> query { joins(:categories).where("lower(title) LIKE ? OR lower(author) LIKE ? OR lower(publisher) LIKE ? OR lower(publication_year) LIKE ? OR lower(country_of_origin) LIKE ? OR lower(description) LIKE ? OR lower (categories.name) LIKE ?", 
    "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase, "%#{query}%".downcase) } 

所以,我错过了一个'连接(:类别)'之前我在哪里。

当我们在我们的模型中定义像has_many或belongs_to这样的关系时,rails活动记录会自动执行此操作,但有必要在我的作用域中声明它,因为我的sql查询响应javascript函数,而不是rails方法。

相关问题