Rails 4 undefined方法`follow_users' - Michael Hartl的教程

时间:2014-08-11 04:19:39

标签: ruby-on-rails ruby

您好我跟随Michael Hartl的Rails教程并收到错误未定义的方法`follow_users'。这是我的代码,它指向第5行:添加了stats.html.erb和用户模型

_stats.html.erb

<% @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.rb

 class User < ActiveRecord::Base
    before_save { self.email = email.downcase }

    before_create :create_remember_token

    validates :name, presence: true

    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: true  

    has_secure_password

    validates :password, length: { minimum: 6 }

    def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.digest(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

    private

    def create_remember_token
      self.remember_token = User.digest(User.new_remember_token)
    end

    has_many :reverse_relationships, foreign_key: "followed_id",
                                   class_name:  "Relationship",
                                   dependent:   :destroy
  has_many :followers, through: :reverse_relationships, source: :follower


   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
end

1 个答案:

答案 0 :(得分:1)

我查看了教程,看来你在用户模型中错过了这种关系:

has_many :followed_users, through: :relationships, source: :followed

这将添加followed_users方法。