Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Seleccionando objetos con rangos usando el número de entrada en Rails

Tengo objetos que tienen un rango de antigüedad mínimo/máximo:

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

Me gustaría seleccionar y devolver estos objetos en función de la preferencia de edad y tipo del usuario al observar si el rango de edad del objeto satisface el número ingresado.

Actualmente estoy atascado con:

Código del controlador:

 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")

Ahora el problema es que necesito elegir un evento de cumpleaños por el número de usuario ingresado, con Rango en el objeto mismo. ¿Hay alguna manera de hacerlo sin pasar por cada objeto?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

Supongo que las asociaciones se ven de la siguiente manera:

 Item has_many :categories Category belongs_to :item

En este caso

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

lo más probable es que falle porque las categories no están unidas con algo como

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

Esto es lo que querrás hacer:

 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')

El uso de BETWEEN de PostgreSQL podría hacer que la consulta se vea mejor y más corta:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!