Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
Picking objects with ranges using input number in Rails

I have objects that have a min/max age range on them:

name: "Event 1"
type: Package # inheritance
min_age: 1
max_age: 8
category_id: 2 # Birthday

I would like to select and return these objects based on user preference of age and type by looking if the object's age range satisfies the inputted number.

Currently I am stuck with:

Controller code:

age = params[:age]
item_type = params[:item_type]
@all_items = Item.where("categories.name = ?", 'birthday')
@events = @all_items.where("(type: #{item_type}) AND ...here I need to lookup if the #{age} variable is within the object range")

Now the problem is that I need to pick a birthday event by inputted user number, having Range on the object itself. Is there a way of doing that without going through every single object?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

@events = @all_items.where("type = #{item_type} AND min_age >= #{age} AND max_age <= #{age}")

I suppose the associations look as follows:

Item has_many :categories
Category belongs_to :item

In this case

Item.where("categories.name = ?", 'birthday')

will most likely fail because categories are not joined with something like

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "categories"

Here is what you'll want to do:

Item.joins(:categories)
    .where(categories: { name: 'birthday' })
    .where("items.type = '#{item_type}' AND items.min_age >= #{age} AND items.max_age <= #{age}")
    .group('items.id')

Using PostgreSQL's BETWEEN might make the query look nicer and shorter:

Item.joins(:categories)
    .where(categories: { name: 'birthday' })
    .where("items.type = '#{item_type}' AND #{age} BETWEEN items.min_age AND items.max_age")
    .group('items.id')
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda