How do I add ranges to my application?
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
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
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
You can either:
- 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.
- 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.