Rails: Invalid One-To-Many Key

I am relatively new to rails. I am trying to establish a one-to-many relationship on rails. However, I think I'm doing something wrong with my foreign_key, since my test fails. My test is as follows:

In user_spec:

  it {should have_many :invitations}

User Model:

  has_many :invitations

Invitation Model:

belongs_to :sender, :class_name => "User"

Invitation:

class CreateInvitations < ActiveRecord::Migration
  def change
    create_table :invitations do |t|
      t.integer :sender_id
      t.string :token

      t.timestamps
    end
  end
end

The error I get from the test:

Failure/Error: it {should have_many :invitations}
       Expected User to have a has_many association called invitations (Invitation does not have a user_id foreign key.)

I am not sure where I am going wrong. Any ideas?

+3
source share
2 answers

Fivell is right. You simply used an alias to associate with the User class. Either change the column name to user_id, or tell rails to use a different foreign key:

invitation.rb

belongs_to :sender, :class_name => "User"

user.rb

has_many :invitations, :foreign_key => "sender_id"
+3
source

, owner_to, has_many

 has_many :invitations , :foreign_key => "sender_id"
+4

All Articles