Derzeit arbeite ich an einer Rails-Anwendung, die eine lokale API hat, wo ich Daten von meinem Hauptmodell Book.rb über eine Suchfunktionalität durch eine Ajax-Anfrage anfordere.Wie rufe ich ein zugeordnetes Attribut von einem anderen Modell in einer SQL-Abfrage auf?
Ich möchte in der Book.rb SQL-Abfrage ein Category.rb-Attribut enthalten.
Die db-Struktur geht so.
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
Hier ist die Abfrage i in diesem Moment auf meinem book.rb perfom.
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
Und das ist, was mein .json.jbuilder aussieht.
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
Ich mag die Book.categories.name
in den Geltungsbereich aufzunehmen, um die Lage sein, i auf dem Buch Modell definiert, so kann ich durch die Kategorien suchen in Bezug auf mein Buch Modell.
Ich habe versucht: 1. niedriger (book.categories) 2. niedriger (book.category.name)
Dies ist ein Blick auf die api ist vorbei 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"
}
]
}
]
Beliebig Tipp, Hinweis oder Referenz ist willkommen!