我正在从事一个具有典型友谊模型的项目。用户类需要具有自引用关系,以便每个用户可以与多个朋友成为朋友,并且可以与多个用户成为朋友……简而言之,我需要本教程中描述的完全相同的东西:
http://railscasts.com/episodes/163-self-referential-association?view=asciicast
但是在看完整个视频之后,我收到了这个错误
uninitialized constant User::Friendship
这是我的用户模型的样子:
class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships
end
友谊模型:
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, class_name => "User"
end
以及friendships_controller的create方法
def create
current_user = User.find(session[:user])
# BELOW LINE HAS THE ERROR
current_user.friendships.build(:friend_id => params[:friend_id])
respond_to do |format|
if @friendship.save
format.html { redirect_to @friendship, notice: 'User Added To your team.' }
format.json { render :show, status: :created, location: @friendship }
else
format.html { render :new }
format.json { render json: @friendship.errors, status: :unprocessable_entity }
end
end
end
我不知道这是否重要,但我没有在视频中使用任何像 Ryan 这样的用户管理插件(我认为他正在使用 OAuth 或其他东西)......另外我没有像他那样通过 nifty_scaffold 生成 Friendship 控制器在本教程中,这是我用来生成脚手架的命令
rails generate scaffold Friendship user_id:integer friend_id:integer create destroy
加上这是我的 ruby 和 rails 版本,如果它有帮助的话......
Rails version 4.1.7
Ruby version 2.0.0p481
我一直在尝试调试我的代码,在互联网上搜索以找出问题所在,但注意到似乎有效。关于可能是什么问题的任何想法?