All threads / How do I add ranges to my application?
Ask A Question


You’re not receiving notifications from this thread.

How do I add ranges to my application?

Samantha O asked in Ruby

Hi in my app I want to have a price classification table where I want to add a range per person...
For example: range_per_person = 1-10, 11-20, 21-30 etc etc.
How can I achieve this? See my schema below.

create_table "pricing_classifications", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name"
t.integer "range_per_person"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false

Hey Sam!

Databases don't understand Ranges like Ruby does, so instead you can add the minimum and maximum values of the range to the database and construct the range from that.

t.integer :minimum
t.integer :maximum
class PricingClassification
  def range
    return nil unless minimum?

You can either:

  1. Make a select that submits "1-10" to a virtual attribute on your model and use Ruby to split on "-" to get minimum and maximum and assign those.
  2. Use Javascript to take the select value and fill out hidden fields for minimum and maximum on the Select change event.

I typically use the second approach so I can keep the backend cleaner.

Do you have an example of number 2? I'm fairly new to programming :S

Not off the top of my head, but I can make a screencast on it. 👍

Awesome! I also send you a slack private message for 2 screencast ideas :S Thank you

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 66,029+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.