我對 Ruby 和 Rails 很陌生,所以這是一種“告訴我我做錯了什么”的問題:
我有一個現有的專案ApplicationRecords。現在我想為has_many其中一個添加一個新關聯(稱為“任務”)。
has_many :assistants, class_name: "User"
我在這里提供類名,因為已經存在另一個關聯has_many :users。(每個任務可以有 0-* 個助手。)
為此創建的正確方法是什么Migration?我創建了以下內容:
class AddAssistantsToTask < ActiveRecord::Migration[6.1]
def change
add_reference :tasks, :assistant, null: true, foreign_key: {to_table: :users}, type: :uuid
end
end
在控制器中,我嘗試將用戶添加到助手關聯中:
if !@task.assistants.includes(@user)
@task.assistants << @user
end
到目前為止,似乎一切都按預期運行。當我嘗試使用 Rails 控制臺查詢添加的用戶時
Task.find("some id").assistants.count
我收到錯誤訊息,該列users.task_id不存在。
在此先感謝您的幫助。
uj5u.com熱心網友回復:
你在錯誤的方向上做陳述
你有一個taskthat has_many assistants,所以foreign_key應該在assistant模型上,在這種情況下是用戶
class AddAssistantsToTask < ActiveRecord::Migration[6.1]
def change
# Add foreign key assistant_id to users that points to tasks
add_reference :users, :assistant, type: :uuid, null: true, foreign_key: { to_table: :tasks }
end
end
現在您可以看到表 Users 上的名稱 assistant_id 沒有意義,所以我將重命名為 assisted_task 或只是 task
class AddAssistantsToTask < ActiveRecord::Migration[6.1]
def change
# Add foreign key assistant_id to users that points to
add_reference :users, :assisted_task, type: :uuid, null: true, foreign_key: { to_table: :tasks }
end
end
has_many :assistants, class_name: "User", foreign_key: :assisted_task_id
或與task
class AddAssistantsToTask < ActiveRecord::Migration[6.1]
def change
# Add foreign key assistant_id to users that points to
add_reference :users, :task, type: :uuid, null: true, foreign_key: true
end
end
has_many :assistants, class_name: "User"
但我同意@BroiSatse,這應該是一個多對多的關系,因為你限制每個用戶只有一個任務
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/474201.html
