mr_muscle
mr_muscle

Reputation: 2900

Rails model accept float only between 0 and 1

I've got model where I stored users percentage progress - specifically it is a percent_progress field, float between 0 (0%) to 1 (100%) in a JourneyProgress model. I'm just wondering how to protect this field so that the wrong numbers don't get there?

Here is my migration:

create_table :journey_progresses do |t|
  t.references :user, foreign_key: true
  t.references :journey, foreign_key: true
  t.float :percent_progress
  t.string :finished_at

  t.timestamps
end

Upvotes: 0

Views: 408

Answers (2)

Abeid Ahmed
Abeid Ahmed

Reputation: 355

If you want to accomplish that you need to install this gem mv-postgresql.

Usage

create_table :journey_progresses do |t|
  t.references :user, foreign_key: true
  t.references :journey, foreign_key: true
  t.float :percent_progress, inclusion: 0.0..1.0
  t.string :finished_at

  t.timestamps
end

Next go to your model and add this line

class JourneyProgress ActiveRecord::Base
  enforce_migration_validations
end

Upvotes: 0

Viktor
Viktor

Reputation: 2773

You can use validations for this:

journey_progress.rb

validates :percent_progress, inclusion: 0.0..1.0

Upvotes: 2

Related Questions