Rails:一对多外键不正确

时间:2012-04-22 20:17:08

标签: ruby-on-rails foreign-keys one-to-many shoulda

我对rails很新。我试图在rails中设置一对多关联。但是,我认为我的foreign_key做错了,因为我的测试失败了。我的测试如下:

在user_spec中:

  it {should have_many :invitations}

用户模型:

  has_many :invitations

邀请函模型:

belongs_to :sender, :class_name => "User"

邀请迁移:

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

      t.timestamps
    end
  end
end

我从测试中得到的错误是:

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.)

我不确定我哪里出错了。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

错误显示问题不在belongs_to中,而在has_many

 has_many :invitations , :foreign_key => "sender_id"

答案 1 :(得分:3)

Fivell是对的。您刚刚使用别名来与User类关联。将列名更改为user_id或告诉rails使用另一个外键:

invitation.rb

belongs_to :sender, :class_name => "User"

user.rb

has_many :invitations, :foreign_key => "sender_id"