简体   繁体   中英

Ruby on Rails - Foreign Keys (foreigner gem)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM