USER (created with devise) 2. Relationships rails g model Relationship follower_id:integer followed_id:integer
create_table "relationships", force: :cascade do |t| t.integer "follower_id" t.integer "followed_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end
Added to each model.
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
#Following has_many :follower, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
has_many :followed, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
#People who follow has_many :follower_user, through: :followed, source: :follower #People being followed has_many :following_user, through: :follower, source: :followed
: point_up: Relationship model can also be divided into "follower" and "followed" By adding: point_up: foreign_key, each can be obtained through the Relationship model.
: point_up: Through each source model
def follow(user_id)
follower.create(followed_id: user_id)
end
def unfollow(user_id)
follower.find_by(followed_id: user_id).destroy
end
def following?(user)
following_user.include?(user)
end
It is used when conditional branching of display with: point_up: html. If user is included in the argument, return true = If true, "Unfollow" is displayed.
②Controller
def create # follow method defined in the User model to follow current_user.follow(params[:user_id]) redirect_to request.referer # Get the URL before the transition and redirect end
def destroy # unfollow unfollow method defined in User model current_user.unfollow(params[:user_id]) redirect_back(fallback_location: root_path) end
def follower #follower list user = User.find(params[:user_id]) @users = user.following_user
end
def followed #followed list user = User.find(params[:user_id]) @users = user.follower_user
end
③Routing
Added for list of create (follow), destroy (unfollow) and follows, followers
resources :users
resource :relationships, only:[:create, :destroy]
get 'follows' => 'relationships#follower'
get 'followers' => 'relationships#followed'
end
④View
Add a link to the part where you want to display the follow button
<% if current_user != user %>
<% if current_user.following?(user) %>
<% = link_to'Unfollow', user_relationships_path (user.id), method:: delete, class: "btn btn-default"%> <% else %> <% = link_to'Follow', user_relationships_path (user.id), method :: POST, class: "btn btn-primary"%> <% end %> <% end %>
Create follower.html.erb and follows.html.erb files in relationships Described in each file as follows
If there is a User in the conditional branch of <% if @ users.count> 0%>, display it in each statement and display it. If not, ** No user ** is displayed
<% if @users.count > 0 %>
<table class="table">
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= @user.name %></td>
No users p> <% end %>
Recommended Posts