8

请求示例应用程序的主页时,我收到以下错误消息(遵循 Michael Hartl 的教程第 11 章):

"ActiveRecord::HasManyThroughSourceAssociationNotFoundError in Pages#home"
"在模型关系中找不到源关联:followed_id。尝试 'has_many :followed_users, :through => :relationships, :source => '。它是以下之一:追随者或:已关注?”

这真的很奇怪,因为我完全按照教程的说明进行操作。我什至复制粘贴了每一个代码片段。

我的用户模型(摘录):

  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

我的关系模型:

  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

我的迁移文件:

  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

我一直在尝试解决这个问题,但我根本不知道问题可能是什么(教程中的确切代码副本)。

4

1 回答 1

21

发现错误:在我的用户模型中,我必须更改

  has_many :followed_users, through: :relationships, source: "followed_id"  

  has_many :followed_users, through: :relationships, source: :followed  

似乎是 Hartl 的教程清单 11.10 http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#code:has_many_following_through_relationships中的一个错字,因为我从那里获得了“来源:”followed_id“”代码。

我从 Hartl 的 github“示例应用程序”中获得了固定代码。

于 2012-06-01T16:24:47.323 回答