0

I see that you can validate a belongs_to at the model level by using validates_presence_of (or something like that), but in the Migration we use a simple belongs_to :owner. There doesn't seem to be an intuitive means to validate the constraint in the database as well.

chrisp
  • 2,181
  • 4
  • 27
  • 35
  • I'm not sure I fully understand, you want to validate data in your migration file? – Donovan Dec 13 '13 at 17:55
  • 1
    You can add a db constraint as follows: `t.integer :owner_id, null: false`. See here: http://stackoverflow.com/questions/5966840/how-to-change-a-nullable-column-to-not-nullable-in-a-rails-migration – Damien Roche Dec 13 '13 at 17:56
  • Actually if you want to validate relationship, and not just id column, you would have to add proper SQL query to your migration. However I would advise you to trust in Rails constraints through validations. – Mike Szyndel Dec 13 '13 at 19:51
  • Donovan: I want to validate the relationship constraint. DamienRoche: yeah I guess that would work. I was surprised that the relationship key column was nullable. :/ – chrisp Dec 13 '13 at 20:10
  • @MichaelSzyndel, that does go against what I have perceived to be rails best practices. At least in my reading it is mentioned, when possible, to let the database do what it does. – chrisp Dec 13 '13 at 20:11
  • Can you link that reading? – Mike Szyndel Dec 13 '13 at 21:50
  • Since I didn't have an exact reference to what I had read months ago here are a few summations: http://stackoverflow.com/questions/13122791/rails-validation-in-model-vs-migration http://stackoverflow.com/questions/2367281/ruby-on-rails-is-it-better-to-validate-in-the-model-or-the-database – chrisp Dec 14 '13 at 20:15

0 Answers0