sjk2426
sjk2426

Reputation: 47

Rails Two Views With One Controller#Action

I created a rails association "user has many follows" currently have lists of user's followers and followings. I want to have 2 links onusers#show to display lists of followers and followings. I know I can render two different views in my follows#index using if else statement but I'm not sure how to go about it. My initial thought was to have rails check which link was clicked (either 'Followers' or 'Followings') but I couldn't find an exact answer. I also thought of creating two different tables (Followers, Followings) but adding 2 same values for 1 action seemed redundant and waste of space.

Here is my FollowsController:

class FollowsController < ApplicationController

  def index
    @follows = Follow.all
    render :index
  end

  def create
    @follow = Follow.create(follow_params)
    redirect_to user_url(@follow.user_id)
  end

  def destroy
    @follow = Follow.find(params[:id])
    @follower_id = @follow.user_id
    @follow.destroy!
    redirect_to user_url(@follower_id)
  end

  private

  def follow_params
    params.require(:follow).permit(:follower_id, :user_id)
  end

end

What would be the best approach?

Upvotes: 0

Views: 1930

Answers (2)

kalelc
kalelc

Reputation: 1527

Example:

def index
  @follows = Follow.all    
  if @follows.present?
    render 'show_with_followers'
  else
    render 'show_without_followings'
  end
end

views

app/views/follows/_show_with_followers.html.erb
app/views/follows/_show_without_followings.html.erb

Upvotes: 3

sjk2426
sjk2426

Reputation: 47

Here is an answer I found so far. I will be using in my view

<%= link_to 'Followers', follows_path(:follows => 'followers') %>
<%= link_to 'Followings', follows_path(:follows => 'followings') %>

and use

def index
    if params["follows"] == 'followers'
      #render followers
    else
      #render followings
    end
  end
end

Upvotes: 1

Related Questions