我正在構建一個 Rails 專案,我有一個用戶,并且該用戶有很多Tests(就像一個瑣事游戲)。我有一個UsersController查詢用戶的地方(稍后將實作登錄)。
在我看來,我有一個“開始”測驗的按鈕。我需要將用戶與測驗相關聯,因為我的User has_many Tests(user_id 是測驗的外鍵)。我的問題是,如何將我的物件傳遞給我的@user物件,TestsController以便我可以將創建的測驗與登錄用戶相關聯?
這是我的UsersController:
class UsersController < ApplicationController
def show
@user = User.find(1)
end
def start_test
redirect_to tests_path
end
end
在我的用戶顯示視圖中,我有:
<p>Welcome <%= @user.name %>!</p>
<%= button_to "Start Test", users_start_test_path %>
單擊按鈕時,我重定向到tests_pathTestsController 中的哪個按鈕:
class TestsController < ApplicationController
def index
# here I need to create the Test belonging to the user
end
end
我是 Rails 的新手,不知道如何將它傳遞@user給,TestsController所以我可以創建屬于用戶的測驗。從理論上講,我什至不需要整體@user,只需要id. 任何幫助將不勝感激。
uj5u.com熱心網友回復:
我認為您應該通過正確設定路由來改進這一點,而不是將控制器操作直接鏈接到另一個控制器。我將創建以下路線。
resources :users do
resources :tests
end
這將迫使您始終擁有一個user_id. 對于您的新測驗路徑,您會得到這個。new_user_test_path(@user)
這將使用基本的 CRUD 操作。因此,要為正確的用戶進行新測驗,請使用def new測驗控制器中的操作。
def new
@user = User.find(params[:user_id]
@new_test = @user.tests.new
end
uj5u.com熱心網友回復:
控制器是獨立的。他們不能共享變數。您可以嘗試向控制器 TestsController 發送用戶 ID 介紹請求(或更好地使用身份驗證系統)。或者直接在 TestsController 中再次呼叫 User.find(1)。
uj5u.com熱心網友回復:
您可以在控制器之間傳遞的唯一變數是通過路由(或會話)的引數。
因此,您可以擁有一個 HTML 表單,將主體傳遞給不同控制器內的操作,或者通過訪問路由并傳遞友好的查詢字串引數(如 ID)來實作我在您的情況下看到的情況。
所以你可以:
<%= button_to "Start Test", users_start_test_path(user_id: @user.id) %>
然后在你的 TestController 中:
class TestsController < ApplicationController
def index
@user = User.find params[:user_id]
end
end
uj5u.com熱心網友回復:
我不喜歡傳遞 current_user 變數,因為它可能會被劫持。
這就是我設定TestsController的方式
class TestsController < ApplicationController
def index
@tests = current_user.tests
end
def new
@test = current_user.tests.new
end
def create
current_user.tests.create(test_params)
end
def show
@test = current_user.tests.find(params[:id]) # this will only find tests scoped to that user
end
def edit
@test = current_user.tests.find(params[:id]) # this will only find tests scoped to that user
end
def update
@test = current_user.tests.find(params[:id]) # this will only find tests scoped to that user
@test.update(test_params)
end
def test_params
params.require(:test).permit()
end
end
這樣,您現在可以將測驗范圍限定為用戶。我假設您有用于用戶管理的設備
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498037.html
