2013-11-25 43 views
0

首先,我对Ruby,Rails和ActiveRecord相当陌生,所以详细的答案将非常感谢。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 

从我一直在读什么,这应该是给我想要什么。但是,当我尝试访问User对象上的.friends时,我收到uninitialized constant Friend错误。 我搜索了一段时间没有运气。我真的不知道如何解决这个问题,但我错过了一些简单的事情。

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

+0

只是为了确认,你在这里使用哪个版本的Rails/ActiveRecord? –

+0

哦,是的,完全忘了,我使用的是Rails 4.0,我会编辑它。 – wiill

+0

你运行的是4.0.0还是4.0.1?刚刚试过这个确切的设置,在Rails 4.0.1下没有问题:https://gist.github.com/timdorr/7647415 –

回答

0

我解决我的问题!

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

作为速战速决,我改名为我的控制器FriendsController ...

class FriendsController < ApplicationController 
    load_and_authorize_resource 
    # ... 
end 

...到... FriendshipsController

class FriendshipsController < ApplicationController 
    load_and_authorize_resource 
    # ... 
end 

......现在一切都运行得很好。 CanCan可以提供一个不同的名称,但对于我的情况Friendships没问题。

我不得不说,我从没想过整个过程中控制器中都存在问题,所以我没有分享这个部分,也许如果我确实有人会看到它。

0

我认为你需要添加一个源选项到has_many :friends关联。

试试这个:

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

没有这个选项,ActiveRecord的自动尝试找到一个相匹配的组织名称(朋友,你的情况)类。

More details here.

+0

谢谢,但不幸的是,它没有帮助,我仍然有同样的问题。 – wiill

+0

如果另外添加class_name选项,它有帮助吗?所以这行看起来像这样:'has_many:朋友,通过::友谊,来源::用户,class_name:“用户”' – rathrio

+0

我之前尝试过,没有运气。 – wiill

相关问题