2016-08-19 17 views
0

現在、ローカルAPIを持つレールアプリケーションで作業しています。ここでは、メインモデルBook.rbのデータにajaxリクエストによる検索機能を要求しています。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を含めることができるようにしたいです。

私が試した:(book.category.name) 2.下部(book.categories) 1下部

これは任意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メソッドではなくjavascript関数にSQLクエリが応答するため、 。

関連する問題