I get the following error message when requesting the home page of my sample app (following Michael Hartl's Tutorial chapter 11):
"ActiveRecord::HasManyThroughSourceAssociationNotFoundError in Pages#home"
"Could not find the source association(s) :followed_id in model Relationship. Try 'has_many :followed_users, :through => :relationships, :source => '. Is it one of :follower or :followed?"
This is really weird, since I followed the instructions of the tutorial exactly. I even copy pasted every single code fragment.
My user model (extract):
class User < ActiveRecord::Base
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: "followed_id"
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
My relationship model:
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
My migration file:
class CreateRelationships < ActiveRecord::Migration
def change
create_table :relationships do |t|
t.integer :follower_id
t.integer :followed_id
t.timestamps
end
add_index :relationships, :follower_id
add_index :relationships, :followed_id
add_index :relationships, [:follower_id, :followed_id], unique: true
end
end
I've been trying to fix this, but I simply don't have any idea left what the problem might be (exact code copy from the tutorial).
Found the error: In my user model I had to change
has_many :followed_users, through: :relationships, source: "followed_id"
to
has_many :followed_users, through: :relationships, source: :followed
Seems to be a typo in Hartl's tutorial Listing 11.10 http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#code:has_many_following_through_relationships, since that's where I got the "source: "followed_id"" code from.
I got the fixed code from Hartl's github "sample app".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With