我正在制作一個任務管理系統并構建一個用戶注冊和登錄系統,而不依賴于設計 gem。目前我面臨一個挑戰,我希望每個用戶(登錄時稱為 current_user)只能看到他們創建的任務(在主頁/索引上列出),包括他們只能編輯或洗掉自己的任務。為此,我def find_user_task給控制器加了一個before action,但是完全無效。請告訴我,我原則上缺少什么?
這是 TasksController 的一部分
before_action :find_task, only: [:show, :edit, :update, :destroy]
before_action :check_login!, except: [:index, :show]
before_action :find_user_task, only: [:edit, :update, :destroy, :publish]
private
def find_task
@task = Task.find(params[:id])
end
def task_params
p = params.require(:task).permit(:name, :due_date, :note, :priority)
p[:status] = params[:task][:status].to_i
return p
end
def find_user_task
@task = Task.find(params[:id])
@task = Task.find_by(id: params[:id], user_id: current_user.id)
# @task = current_user.tasks.find(params[:id])
end
end
這是模型任務的一部分
class Task < ApplicationRecord
validates :name, :note, :due_date, :status, :priority, presence: true
has_many :category_tasks
has_many :categories, through: :category_tasks
belongs_to :user, foreign_key: true, optional: true
這是模型用戶的一部分
require 'digest'
class User < ApplicationRecord
validates :email, presence: true, uniqueness: true
validates :password, confirmation: true, length: { minimum: 4 }, presence: true
validates :role, presence: true, uniqueness: true
has_many :tasks, dependent: :destroy
uj5u.com熱心網友回復:
希望我能在這里為您提供幫助...首先,在這段代碼中:
@task = Task.find(params[:id])
@task = Task.find_by(id: params[:id], user_id: current_user.id)
您的第二行覆寫第一行,因此您可以洗掉第一行。關于您的問題,我建議您根據您的模型和關系來做到這一點......這比在控制器中處理它更容易(而且更好)。問題是你想確保一個任務屬于一個用戶(并且可以有 N 個任務)。在創建任務之前,請確保將該任務的 user_id 設定為 current_user.id。它會是這樣的:
class User < ApplicationRecord
has_many :tasks
end
對于您的任務模型:
class Task < ApplicationRecord
belongs_to :user
end
然后,在任務控制器上的創建操作(或執行該操作的任何位置)上,請務必為您的 current_user 設定 user_id:
@task.user_id = current_user.id
如果您仍然沒有為任務創建 foreign_key (user_id),只需進行遷移,如下所示:
rails g migration AddUserIdToTask user_id:integer
rails db:migrate
然后,如果你做對了,你可以通過關系獲取特定用戶的任務:user.tasks(或者,在你的情況下):
@tasks = current_user.tasks
對于除錯和測驗,rails 控制臺是您的朋友......為用戶創建一個任務,然后檢查控制臺是否正確設定了 user_id。然后嘗試加載該 user.tasks 并查看它是否按預期帶來了它們。一步一步去檢查。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452376.html
標籤:轨道上的红宝石
