我一直收到错误
uninitialized constant User::Relationships
在完成 rails 教程的第 11 章时。
这是我在浏览器中登录时尝试访问主页时的完整错误。
Extracted source (around line #11):
8: </a>
9: <a href="<%= followers_user_path(@user) %>">
10: <strong id="followers" class="stat">
11: <%= @user.followers.count %>
12: </strong>
13: followers
14: </a>
我已经多次阅读本章并检查了每一行代码,但有时你的眼睛会欺骗你,所以这里是剩下的代码
用户.rb
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
has_many :microposts, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationships",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
before_save { |user| user.email = email.downcase}
before_save :create_remember_token
validates :name, presence:true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX},
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6}
validates :password_confirmation, presence: true
def feed
Micropost.where("user_id =?", id)
end
def following?(other_user)
relationships.find_by_followed_id(other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
这是类本身
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
这就是教程中的内容...我添加了 :follower_id 以防万一,但它仍然无法正常工作。
而且我还建立了一个relationship_controller。
class RelationshipsController < ApplicationController
before_filter :signed_in_user
def create
@user = User.find(params[:relationship][:follower_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
def destroy
@user = Relationship.find(params[:id]).followed
current_user.unfollow!(@user)
respond_to do |format|
format.html { redirect_to @user }
fromat.js
end
end
结尾
而在路线...
resources :users do
member do
get :following, :followers
end
end
发生错误的页面如下所示:
<% @user ||= current_user %>
<div class = "stats">
<a href ="<%= following_user_path(@user)%>">
<strong id="following" class="stat">
<%= @user.followed_users.count %>
</strong>
following
</a>
<a href="<%= followers_user_path(@user) %>">
<strong id="followers" class="stat">
<%= @user.followers.count %>
</strong>
followers
</a>
</div>
当我删除第二部分时,第二块之前的第一部分代码可以完美运行。只是由于某种原因没有建立“追随者”关系。我在控制台中使用它并没有调用它,而 user.followed_users 确实有效。我已经玩了四个小时,已经放下桌子并重建了它,但我无法让它工作。
我之前尝试查看堆栈溢出并发现:
Ruby 错误(未初始化的常量 User::Relationship)
但是那里的解决方案都没有帮助。谢谢你的帮助!