【发布时间】:2015-06-26 02:34:09
【问题描述】:
我有这样关系的模型
class User < ActiveRecord::Base
has_many :identities
has_many :activities
end
class Identity < ActiveRecord::Base
belongs_to :user
has_many :manifests
has_many :activities, through: :manifests
end
class Activity < ActiveRecord::Base
belongs_to :user
has_one :link
has_many :manifests
has_many :identities, through: :manifests
end
class Manifest < ActiveRecord::Base
belongs_to :activity
belongs_to :identity
end
class Link < ActiveRecord::Base
belongs_to :activity
end
但是当我尝试打电话时
user.activities
它会引发错误
ActiveRecord::AssociationNotFoundError: Association named 'user' was not found on Link; perhaps you misspelled it?
这让我很困惑,因为我没有将用户关系放在链接模型上。有人可以帮我吗?
【问题讨论】:
-
activity 表是否有 user_id 作为外键?您可能没有指定关联。如果您在 db 级别没有关联,则使用以下内容创建一个新迁移:def change add_reference :activities, :user, index: true, foreign_key: true end
-
是的,活动表的 user_id 为 fk
-
我无法重新审视这个github.com/maxcal/sandbox/tree/31063937。我猜错误可能是您的
user变量根本不是用户。尝试使用abort user.class.name进行验证。 -
你是怎么得到
user的? -
User.first,我在控制台上试过了。搞砸之后,我认为数据库的外键约束可能会导致它。或者rails有错误。我试图在活动记录 gem 上调试它,但在调用链接对象时发现错误。这很奇怪,因为我不写包含查询。链接对象尝试将用户作为父级。我觉得这很奇怪。
标签: ruby-on-rails ruby-on-rails-4 rails-activerecord model-associations