Ask A Question

Notifications

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
end

Reply

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?
    (minimum..maximum)
  end
end
Reply

Hi Chris,
Thanks for the reply. How do I get this in a dropdown? Like this example: https://www.wix.com/corvid/forum/community-discussion/single-dropdown-filter-using-a-range

Reply

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.

Reply

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

Reply

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

Reply

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

Reply
Join the discussion
Create an account Log in

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

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

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