Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!