0

I have a table Student(class_id(integer),marks(integer),rank(integer))

In my Seeds.rb file i have written something like this to make entry to table

Student.create(class_id:2 ,marks:"abcdef", rank: 2)

when i add these data to table by rake db:seed command ,i was expecting i would not be allowed to add this ,because for marks field of student, string is being inserted instead of integer.But rails added this record without any problem.

so how do i ensure this kind of entry doesnot happen and my table ensures type check.Me a newbie to rails and postgres

2
  • 1
    Ok, add a validation inside the Student model to check the same. Then you will get the error. Commented Feb 28, 2016 at 18:13
  • @arupRakshit okay this is at the model level,but cant i do something at the db level ,so postgres donot provide something for it at db level? Commented Feb 28, 2016 at 18:21

1 Answer 1

1

So, a validation like below will work. Add it to the Student model.

validates :marks, numericality: { only_integer: true }

Whenever you will try to create a Student record, this validation will be called by Rails. If it passes then the recored will be created, otherwise not. There are methods to check if a record is valid or not in rails.

Read the guide to know how validation works in rails.

Sign up to request clarification or add additional context in comments.

3 Comments

@Rumour May be. But Doing it in ActiveRecord will have benefits when you are in Rails.
i was expecting a error or exception , but the above statement simply doesnot add the row which contains a field who's value is wrong.
@Rumour have you done a little study on Rails. Seems not. So please go through guides.rubyonrails.org/active_record_validations.html . Try Student.create!(class_id:2 ,marks:"abcdef", rank: 2) and see what goes on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.