3

私はレールに比較的慣れていません。Railsで1対多の関連付けを設定しようとしています。ただし、テストが失敗しているため、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.)

どこが間違っているのかわかりません。何か案は?

4

2 に答える 2

4

エラーは、問題が belongs_to ではなく、has_many にあることを示しています

 has_many :invitations , :foreign_key => "sender_id"
于 2012-04-22T20:34:35.910 に答える
3

ファイベル そうです。User クラスへの関連付けにエイリアスを使用しました。列名を次のように変更するuser_idか、Rails に別の外部キーを使用するように指示します。

招待.rb

belongs_to :sender, :class_name => "User"

user.rb

has_many :invitations, :foreign_key => "sender_id"
于 2012-04-22T20:24:42.113 に答える