ruby-on-rails - 如何在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 %>
解决方案
首先在用户和任务之间建立关联:
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 %>
您可以在此处使用部分来减少重复。
推荐阅读
- javascript - 如何删除 ngx-bootstrap dropdownToggle 添加的文档点击事件处理程序?
- flyway - 自动创建数据库
- java - 您如何更新文档中的文档?MongoDB Java
- reactjs - 如何在将道具值传递给另一个组件时避免箭头功能?
- php - 如何从 Codeigniter 3.1.9 的 url 中删除 index.php
- node.js - Node.js 和 amcharts4 - 使用 TypeSript 或 ES6 导入错误“意外令牌导出”
- c++ - 更简洁的方式来声明高维向量
- java - 使用 java cv 时在 android studio 上出现构建错误
- reactjs - 在我的反应原生项目中显示没有互联网连接
- angular - Angular 5:新数据与旧数据合并