Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord adding rating range in migration file

class AddRatingToBooks < ActiveRecord::Migration
  def up
    add_column :books, :rating, :integer
  end

  def down
    remove_column :books, :rating
end

I have the following snippet of code in my db/migrate/, I'm trying to add ratings to my books table, where it would be in a range from 0-100, but I'm not sure how to add that here, all i could find was querying with ranges. I'm sure it's simple I'm just not there yet.

like image 352
Diego Avatar asked Jun 14 '26 11:06

Diego


1 Answers

You don't need to specify the range of integer values in your migration file. The migration file is simply used to add the database column to store the rating. This is not the place to add validations.

You should use your Book model to specify a validation that ensures your ratings fall within a certain range. Something like this:

class Book < ActiveRecord::Base
  validates :rating, :inclusion => { :in => 0..100 }
end

I would highly recommend reading the Rails guides on both migrations and validations.

like image 145
Joel Brewer Avatar answered Jun 16 '26 07:06

Joel Brewer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!