1
我對連接表中的外鍵感到困惑。我試圖建立一個連接表,將我的用戶和指南模型鏈接起來形成一個FavoriteGuideline表(即用戶可以選擇一個最喜歡的指南)。加入表和外鍵
我的錯誤是:
'預計FavoriteGuideline有belongs_to的關聯稱爲 喜愛(FavoriteGuideline沒有favorite_id外鍵)'
我favorite_guideline.rb是
class FavoriteGuideline < ActiveRecord::Base
belongs_to :user
belongs_to :guideline
belongs_to :favorite, class_name: 'User', foreign_key: 'favorite_id'
attr_accessible :user, :favorite, :guideline
end
and my favorite_guideline_test.rb is
require 'test_helper'
class FavoriteGuidelineTest < ActiveSupport::TestCase
should belong_to(:user)
should belong_to(:favorite)
test "that creating a favorite works without raising an exception" do
assert_nothing_raised do
FavoriteGuideline.create user: users(:eve), guideline: guidelines(:three)
end
end
end
而且我的數據庫遷移
class CreateFavoriteGuidelines < ActiveRecord::Migration
def change
create_table :favorite_guidelines do |t|
t.integer :user_id
t.integer :favorite_id
t.integer :guideline_id
t.timestamps
end
add_index :favorite_guidelines, [:user_id]
add_index :favorite_guidelines, [:favorite_id]
add_index :favorite_guidelines, [:guideline_id]
end
end
我愛你。謝謝。 – tessad 2013-02-12 08:04:04