首页 > 解决方案 > 如何在rails中显示与登录用户相关的数据

问题描述

我正在尝试显示与登录用户相关的任务,但在我的 html 页面上,除了

标记数据

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

路线.rb

  get 'all_task' => 'task#all_task'

任务.erb

 <p>All Task</p>

 <% if user_signed_in? %>

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

标签: ruby-on-railsrubyruby-on-rails-4rubygems

解决方案


首先在用户和任务之间建立关联:

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

然后设置路由和控制器:

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

请注意,当您有这样的路由显示属于当前用户的资源时,您应该使用回调提前保释并重定向用户登录,而不是使用if current_user.present?并给出对用户毫无意义的响应。这段代码应该 DRY:ed 到您的 ApplicationController 中(更好的是不要重新发明身份验证轮)。

您可以通过以下方式链接到用户任务:

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

在您看来,您需要遍历返回的任务:

# 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 %>

您可以在此处使用部分来减少重复。


推荐阅读