如何在 Rails 模型中引入 has_one_belongs_to_one 关联?

How can I introduce a has_one_belongs_to_one association in Rails model?

我的 Rails 应用程序有用户和用户创建的任务。用户还可以创建任务并将另一个用户分配给它。我不太确定如何在这里建立关联。

我知道因为任务是由用户创建的,所以我可以有如下关联,

class User
  has_many :tasks, dependent: :destroy, foreign_key: :user_id
end
class Task
  belongs_to :user
end

我还想在 Task 模型中为创建者添加一个关联,但我不知道该怎么做,因为创建者也将是 User [=28= 的一个实例] 并且我已经与 User

建立了 belongs_to 关联

我尝试通过以下方式在 Task 模型中为创作者添加关联,但没有成功。

has_one :user, foreign_key: :creator_id, class_name: "User"

由于您已经定义了 belongs_to :user 方法,因此该关联已采用方法 @task.user。您不能为不同的方法使用相同的名称,因此您必须为该关联使用不同的名称。

关联名称不必与模型相同。您可以将创作者协会命名为其他名称,例如“创作者”:

has_one :creator, foreign_key: 'creator_id', class_name: "User"

由于任务有一个创建者的外键,您应该能够对两个关联使用 belongs_to:

class Task
  belongs_to :user
  belongs_to :creator, foreign_key: 'creator_id', class_name: 'User'
end

下面讨论一下has_onebelongs_to的区别:What's the difference between belongs_to and has_one?

无论哪种方式都可以:

@task.user    # the User who is assigned the task
@task.creator # the User who created the task