ActiveRecord多对多自引用未初始化的常量错误

时间:2013-11-25 19:14:21

标签: ruby-on-rails ruby activerecord many-to-many

首先,我是Ruby,Rails和ActiveRecord的新手,所以非常感谢您的详细解答。

我想要实现的是一个与自身有多对多关系的模型。它基本上是“用户有很多朋友(又名用户)”设置。

这就是我目前对我的桌子所拥有的:

create_table "friendships" do |t|
  t.integer "user_id"
  t.integer "friend_id"
end

create_table "users" do |t|
  t.string   "email",
  t.string   "username",
  # etc.
end

这就是我对模特的看法:

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: "User"
end

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, through: :friendships
end

从我读过的内容来看,这应该是我想要的东西。但是,当我尝试访问.friends对象上的User时,收到uninitialized constant Friend错误。 我没有运气地搜索了一会儿。我真的不知道如何解决这个问题,它一定是我错过的简单。

如果有帮助,我在Ruby 2.0.0p247上使用Rails 4.0.1。

2 个答案:

答案 0 :(得分:0)

我认为您需要为has_many :friends关联添加源选项。

试试这个:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, through: :friendships, source: :user, class_name: "User"
end

如果没有此选项,ActiveRecord会自动尝试查找与关联名称匹配的类(在您的情况下为Friend)。

More details here.

答案 1 :(得分:0)

我解决了我的问题!

最后,这甚至不是模型或关系问题,而是CanCan由于我的控制器名称而无法找到Friend模型的问题。

作为快速修复,我重命名了我的控制器FriendsController ...

class FriendsController < ApplicationController
  load_and_authorize_resource
  # ...
end

...到FriendshipsController ...

class FriendshipsController < ApplicationController
  load_and_authorize_resource
  # ...
end

......现在一切都运行得很好。可以向CanCan提供不同的名称,但对于我的案例Friendships是正常的。

我不得不说,从来没有想到这个问题在整个控制器中都是正确的,所以我没有分享那部分,也许如果我做了某人就会看到它。

相关问题