Better Ruby/Rails query with arel or sql

Let's say the premise of the site is for users to review outfits. So the main model of the site is a repository of outfits.

Fashion changes every season so whether or not the outfit is included for review that season depends on a variety of factors.

class Season < ApplicationRecord end  def Category < ApplicationRecord   has_many :appearances, as: :appearable end  def Style < ApplicationRecord   has_many :appearances, as: :appearable end  def Objective   has_many :appearances, as: :appearable end  def Outfit  has_many :appearances, as: :appearable end 

The appearance table is a polymorphic table that connects each item to the item below/above it. For example, an outfit can belong to 3 different seasons because it has 3 appearances.

Categories are pretty much the same every year ("Coats", "Shoes", "Shirts", "Dresses"), Styles belong to Categories, for example, we can narrow down the 'shoecategory -> "Modern", "Retro", etc., then the Objective belongs to the Style --> "To fit in with millennials", "To fit in with hippies", "To fit in with retirees", and finally, theOutfit` belongs to Style.

Right now, I want each object to be able be linked to the other objects like: `outfit.seasons' --> which season does the outfit occur in. 'season.oufits' -> what outfits are in the season.

Current code:

def categories_for_season   ids = Appearance.where(parentable_id: "Season", parentable_id: id, appearable_type: "Category").pluck(:appearable_id)   Category.where(id: ids) end  def styles_for_category   ids = Appearance.where(parentable_id: "Category", parentable_id: id, appearable_type: "Style").pluck(:appearable_id)   Style.where(id: ids) end 

This allows be to find season.styles by going through these associations:

def styles #for exam   array = []   categories_for_season.map { |cat| array << cat.styles_for_category.pluck(:id) }   Style.where(id: array.flatten) end 

I have two more associations for style/objective, and then objective/outfit that finally allows me to find outfits for season (season.outfits).

Of course this runs like this:

  1. Find season
  2. Find all categories for season, map ids
  3. Find the categories
  4. Find all styles for categories, map ids
  5. Find the styles
  6. Find all objectives for styles, map id
  7. Find objectives
  8. Find all objective for objective, map ids
  9. Find outfits!

How can improve this without linking outfit directly to season?

Replay

Category: ruby Time: 2016-07-29 Views: 0

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.210 (s). 12 q(s)