I’m getting rather confused about foreign keys in the join table. I’m trying to build a join table that links my user and guideline models to form a FavoriteGuideline table (i.e. user can pick a favorite guideline).
My error is:
‘Expected FavoriteGuideline to have a belongs_to association called
favorite (FavoriteGuideline does not have a favorite_id foreign key)’
My favorite_guideline.rb is
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
And my database migration is
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
If I understand correctly, FavoriteGuideline is meant to be the association table. Favorite is just an alias for FavoriteGuideline.
So your model should be:
And your test should have the line
instead of
And your migration should probably have favorite_id as the primary key:
Then you will also need to finish defining the association with
has_manyinuser.rbandguideline.rb