如何显示我拥有的所有粉丝? 我已经做了以下可能,但我不知道如何显示正在关注的用户。此外,我不知道如何展示来自所有人的帖子"我跟随"。
#/app/controllers/followers_controller.rb
class FollowersController < ApplicationController
def index
@user = current_user
@followers = Follower.where(following_id: params[:user_id])
end
def create
if current_user
@user = User.find(params[:user_id])
@follower = Follower.new(follower_params)
@follower.user_id = current_user.id
@follower.following_id = @user.id
if @user != current_user
@follower.save
end
redirect_to root_url
end
end
def follower_params
params.require(:follower).permit(:user_id, :following_id)
end
end
#/app/views/followers/index.html.erb
<% @followers.each do |f| %>
<b><%= f.user_id %></b>
<br/>
<% end %>
#/app/models/follower.rb
class Follower < ActiveRecord::Base
validates_uniqueness_of :following_id, scope: :user_id
belongs_to :user
end
#/app/models/user.rb
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
before_save { self.username = username.downcase }
before_save { self.email = email.downcase }
validates_confirmation_of :password
validates_presence_of :password, on: :create, length: { minimum: 8 }
validates :email, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 255 }
validates :username, presence: true, length: { minimum: 6, maximum: 30 }, uniqueness: { case_sensitive: false }
validates :bio, length: { maximum: 140 }
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :followers, dependent: :destroy
has_attached_file :avatar,
styles: {
thumb: '75x75#',
small: '150x150#'
}
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
has_attached_file :banner,
styles: {
thumb: '75x75>',
small: '150x150>'
}
validates_attachment_content_type :banner, content_type: /\Aimage\/.*\Z/
def self.authenticate(username, password)
user = find_by_username(username)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
答案 0 :(得分:1)
因此,您可以对模型的设置进行一些调整。
由于关注者也是用户,这意味着您的Follower
(我将重命名为Following
应该是一个联接表。)
class Following < ActiveRecord::Base
belongs_to :leader, class_name: 'User'
belongs_to :follower, class_name: 'User'
end
和您的用户模型:
class User < ActiveRecord::Base
has_many :followings, foreign_key: :follower_id,
dependent: :destroy
has_many :leaders, through: :followings
has_many :reverse_followings, foreign_key: :leader_id,
class_name: 'Following',
dependent: :destroy
has_many :followers, through: :reverse_followings
end
请注意,您必须通过更改迁移以包含所需的列来实现此目的。
然后你应该可以致电user.followers
并运行迁移。 希望这有帮助吗?