Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Join tables confusion (Testing Friendships)

I'm getting rather confused about foreign keys in the join table. I'm trying to follow the tutorial to build a slightly different join table to Jason's - mine 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

1 Answer

I solved it by changing

class FavoriteGuidelineTest < ActiveSupport::TestCase should belong_to(:user) should belong_to(:favorite)

to

class FavoriteGuidelineTest < ActiveSupport::TestCase should belong_to(:user) should belong_to(:guideline)

Still haven't got to the end though so not sure if my association will work out!