簡體   English   中英

Rails 4未定義方法“ followed_users”-Michael Hartl的教程

[英]Rails 4 undefined method `followed_users' - Michael Hartl's Tutorial

嗨,我正在關注Michael Hartl的Rails教程,並收到錯誤未定義方法`followed_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

我看了教程,看來您的用戶模型中缺少這種關系:

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

這將添加followed_users方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM