【问题标题】:Rails: Association was not found; perhaps you misspelled it?Rails:未找到关联;也许你拼错了?
【发布时间】:2013-04-26 16:27:30
【问题描述】:

我有一个User 模型,它与Publication 模型具有has_many :through 关系。 Publication 模型又与Author 具有has_many :through 关系:

class User < ActiveRecord::Base
  has_many :library_publications, :dependent => :destroy, :class_name => "Library::Publication"
  has_many :publications, :through => :library_publications
end

class Library::Publication < ActiveRecord::Base
  belongs_to :publication
  belongs_to :user
end

class Publication < PublicationBase
  has_many :library_publications, :dependent => :destroy, :class_name => "Library::Publication"
  has_many :users, :through => :library_publications
  has_many :publication_contributions, :dependent => :destroy, :class_name => "Publication::Contribution"
  has_many :authors, :through => :publication_contributions
end

class Author < AuthorBase
  has_many :publication_contributions, :dependent => :destroy, :class_name => "Publication::Contribution"
  has_many :publications, :through => :publication_contributions
end

class Publication::Contribution < Publication::ContributionBase
  belongs_to :publication, :class_name => "Publication"
  belongs_to :author, :class_name => "Author"
end

据我所知,所有关联都写得正确。但是,当我尝试从用户那里急切加载作者时:

@user.library_publications.includes(:publication => [:authors])

我收到此错误:

Association named 'authors' was not found; perhaps you misspelled it?

这可能是什么原因?

【问题讨论】:

  • 我认为你这里有一个错字:class Publication::Contribution &lt; Publication::ContributionBase
  • 好眼光。我应该解释一下。 Publication::ContributionBase 是一个 STI 类。此示例中还有其他几个。不过,也许 STI 以某种方式干扰了这种关联?
  • 这就是我坚持的。但我还不确定。

标签: ruby-on-rails activerecord jointable


【解决方案1】:

经过一番试验,我发现publication 的所有关联都被破坏了。这导致我寻找更大的问题,最终我发现这个问题是由被命名空间的连接表之一引起的,Library::Publication。当我取消命名空间时,publication 的关联又开始工作了。

不过,我不确定为什么会这样。如果有人有解释,请分享。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多