【问题标题】:Could not find the source association(s) :followed_id in model relationship in Rails 3.2在 Rails 3.2 的模型关系中找不到源关联:followed_id
【发布时间】:2012-05-22 22:12:22
【问题描述】:

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

“页面#home 中的 ActiveRecord::HasManyThroughSourceAssociationNotFoundError”
“在模型关系中找不到源关联 :followed_id。尝试 'has_many :followed_users, :through => :relationships, :source => '。它是 :follower 还是 :followed 之一?”

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

我的用户模型(摘录):

  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

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

【问题讨论】:

  • 您可以将您的解决方案作为答案发布并接受它,这样人们就不会花时间阅读问题而只是发现您已经解决了它。
  • 这是我首先尝试的,但它不会让我说“低于一定声誉的用户无法回答他们自己的问题”。无论如何,我会将编辑放在问题之上。很抱歉,如果您阅读了整个问题却发现我已经解决了它。

标签: ruby-on-rails associations relationship railstutorial.org


【解决方案1】:

发现错误: 在我的用户模型中,我不得不改变

  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 中的一个错字,因为我从那里获得了“source:”followed_id”代码。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多