Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: One-to-many association fails due to foreign key validation

I have set up a one-to-many association in rails, but my test keeps on failing due to a foreign-key not set up properly. I was wondering if anyone had any advice.

I have two models - rota and user. I want a rota to be "created" by a user. A user can create more than one rota.

Test failing

*In rota_spec:*

it {should belong_to :creator}
Expected Rota to have a belongs_to association called creator (Rota does not have a creator_id foreign key.)

*In user_spec:*

it {should have_many :created_rotas}
Expected User to have a has_many association called created_rotas (Rota does not have a creator_id foreign key.)

Rota.rb

  belongs_to :creator, :class_name => "User"

User.rb

  has_many :created_rotas, :class_name => "Rota", :foreign_key => "creator_id"

Migration

class AddCreatorToRotas < ActiveRecord::Migration
  def change
    add_column :rotas, :creator_id, :string
  end
end
like image 847
Karan Avatar asked Jul 29 '12 00:07

Karan


1 Answers

You must to run

rake db:test:prepare
like image 138
Dougui Avatar answered Sep 30 '22 06:09

Dougui