smith
smith

Reputation: 373

How can show the data related to logged in user in rails

I am trying display the task related to logged in user but on my html page nothing show except the

tag data

task_controller.rb

 class TaskController < ApplicationController
      def all_task
       if current_user.present?
         @all_task = Task.find_by_user_id(@current_user.id)
         render template: 'task/allTask'
       end
    end
 end

routes.rb

  get 'all_task' => 'task#all_task'

task.erb

 <p>All Task</p>

 <% if user_signed_in? %>

   <%@all_task.daily_task  %>
   <%@all_task.date  %>
   <%@all_task.created_at  %>
 <%end %>

Upvotes: 0

Views: 984

Answers (2)

max
max

Reputation: 101811

Start by setting up an assocation between users and tasks:

class User < ApplicationRecord
  # ...
  has_many :tasks
end

Then setup the route and controller:

get '/user/tasks', to: 'users/tasks#index', as: :user_tasks
# app/controllers/users/tasks_controller.rb
module Users
  class TasksController < ApplicationRecord
    before_action :authenticate_user!

    # display all the tasks belonging to the currently signed in user
    # GET /user/tasks
    def index
      @tasks = current_user.tasks
    end

    private

    # You don't need this if your using Devise
    def authenticate_user!
      unless current_user 
        redirect_to '/path/to/your/login', 
          notice: 'Please sign in before continuing' 
      end
    end
  end
end

Note that when you have a route like this that displays resources that belong to the current user you should use a callback to bail early and redirect the user to sign in instead of using if current_user.present? and giving a response which is meaningless to the user. This code should be DRY:ed into your ApplicationController (even better yet is to not reinvent the auth wheel).

You can link to the users tasks with:

<% if current_user.present? %>
  <%= link_to 'My tasks', user_tasks_path %>
<% end %>

In your view you need to iterate across the returned tasks:

# app/views/users/tasks/index.html.erb
<p>All Tasks</p>

<% if @tasks.any? %>
  <% @tasks.each do |task| %>
    <%= task.daily_task  %>
    <%= task.date  %>
    <%= task.created_at  %>
  <% end %>
<% else %> 
  <p>You don't have any tasks.</p>
<% end %>

You can cut duplication here by using partials.

Upvotes: 2

Taimoor Hassan
Taimoor Hassan

Reputation: 417

Can you make sure if the instance variable @current_user is defined? If not, try the following:

 class TaskController < ApplicationController
      def all_task
       if current_user.present?
         @all_task = Task.find_by_user_id(current_user.id)
         render template: 'task/allTask'
       end
    end
 end

instead of

 class TaskController < ApplicationController
      def all_task
       if current_user.present?
         @all_task = Task.find_by_user_id(@current_user.id)
         render template: 'task/allTask'
       end
    end
 end

Upvotes: 0

Related Questions