Skip to content

Instantly share code, notes, and snippets.

View rodloboz's full-sized avatar

Rui Freitas rodloboz

View GitHub Profile
resources :users, path: '/', param: :username, only: %i[show] do
post :follow, to: 'users/follows#create', as: :follow
delete :follow, to: 'users/follows#destroy', as: :unfollow
end
class CreateFollows < ActiveRecord::Migration[6.0]
def change
create_table 'follows' do |t|
t.integer 'following_id', null: false
t.integer 'follower_id', null: false
t.timestamps null: false
end
add_index :follows, :following_id
# app/models/user.rb
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", {value: login.strip.downcase}]).first
end
module AvatarHelper
def avatar_url(user)
if gravatar?(user)
gravatar = Digest::MD5::hexdigest(user.email).downcase
"http://gravatar.com/avatar/#{gravatar}.png?s=200"
else
'default_avatar.png'
end
end
class ApplicationController < ActionController::Base
# ...
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:email, :password, :username, :full_name])
devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password, :username])
class AddAttributesToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :full_name, :string
add_column :users, :username, :string
add_index :users, :username, unique: true
add_column :users, :about, :text
end
end
import { Controller } from 'stimulus';
export default class extends Controller {
static targets = [ 'followerCount', 'followerMessage' ]
connect() {
this.update();
};
update() {
<div id="follow-btn">
<% if current_user.is_following?(user) %>
<%= link_to user_unfollow_path(user.username), method: :delete,
data: {
action: 'ajax:success->follow#update'
},
remote: true do
%>
<button class="btn btn-blue ml-4">Unfollow</button>
<% end %>
<li class="mr-8">
<span id="followers-count"
class="font-bold"
data-target="follow-button.followerCount"><%= @user.followers_count %></span>&nbsp
<span data-target="follow-button.followerMessage"></span>
</li>
class Follow < ApplicationRecord
belongs_to :follower, class_name: 'User', foreign_key: 'follower_id',
counter_cache: :followings_count,
inverse_of: :following_relationships
belongs_to :following, class_name: 'User', foreign_key: 'following_id',
counter_cache: :followers_count,
inverse_of: :follower_relationships
end