0

I'm new to RoR so don't be surprised with possible dumm things I may say... sorry in advance...

I'm trying to create foreign keys constrainsts between two models "Addendum" and "Contract"

the ActiveRecord is now like this

class Addendum < ActiveRecord::Base
    belongs_to :contract  
end


class Contract < ActiveRecord::Base
    has_many :addendums
end

So, I need that the program only lets creating a new Addendum if it will be associated to an existing contract. I've installed the gem foreigner and created this migration:

class AddingForeignKeys < ActiveRecord::Migration
  def change
    add_foreign_key(:contracts, :addendums)
  end
end

run rake db:migrate

and expected to see changes on the ActiveRecord::Base (indicating the foreign key constraint) but no alteration occur

What am I doing wrong?

NunoRibeiro
  • 511
  • 2
  • 7
  • 22

1 Answers1

0

it is enough to have a contract_id column in the Addendum table, create the association ( in your case has_many and belongs_to) and into the Addendum model a validation constraint:

validates :contract, presence: true

hope helps

Federico

fedetaglia
  • 238
  • 3
  • 10
  • So, what's the difference between the validates and foreign key? – NunoRibeiro May 05 '14 at 01:58
  • sorry have to correct my post actually you should validate not the field but the name, I updated my previous post with: validates :contract, presence: true this not only will check the presence of the field but also the presence of the actual Contract on the db (this is what you want) – fedetaglia May 05 '14 at 02:23
  • Thanks, I think that will work... since you're there, what about a association has_and_belongs_to_many ? How can I validate? for instance I have `Addendum.rb: has_and_belongs_to_many :pests` and `Pest.rb: has_and_belongs_to_many :addendums` should I had `validates :pest, presence: true` and `validates :addendum, presence: true` ? – NunoRibeiro May 05 '14 at 02:43
  • I think that if you want validation is better to use a has_many :through model instead. check this guide: http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many – fedetaglia May 05 '14 at 02:56