为多态的has_many:through]激活等效于Laravel ORM`attach()`方法的ActiveRecord >> [

问题描述 投票:0回答:1
我正在从“ Laravel ORM”过渡到“ Rails Active Record”,但我找不到如何执行以下操作:

$this->people()->attach($person['id'], ['role' => $role]);

Laravel代码片段的说明

People是与通过$this类通过Role访问的类的多态关联。上面的函数在中间表(角色/人员)中创建一条记录,如下所示:

id: {{generically defined}} people_id: $person['id'] role: $role peopleable_type: $this->type peopleable_id: $this->id

如何在Laravel端定义关联:

class XYZ { ... public function people() { return $this->morphToMany(People::class, 'peopleable')->withPivot('role','id'); } ... }

我在Ruby中的努力

这是我在Ruby中建立关联的方式:

class Peopleable < ApplicationRecord belongs_to :people belongs_to :peopleable, polymorphic: true end class People < ApplicationRecord has_many :peopleables end class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end

我已经看到了操作<<,但我不知道在触发此操作时是否有任何方法可以在数据透视表上设置其他值。 [在这种情况下,rolespeopleables表;我在此应用程序中可以互换使用这两个术语。]

PS。因此,基本上的问题是,如何在ActiveRecord中的多态多关联中在数据透视表上定义其他值,并在启动附件关系时动态设置这些值]

功能说明

我们的应用程序有一个无限的[通常来说,没有计算限制!]内容类型:帖子,小说,诗歌等。

这些内容类型中的每一个都可以与扮演某些角色的个人相关联:编辑,作者,翻译等。>

因此,例如:

X是Post#1的翻译器。 X,Y和Z是帖子#1的作者。

[有一个不同的People模型,每种内容类型都有自己的唯一模型[例如:PostPoem等]。

:through

的概念是指[Role类”或“数据透视表”(无论您希望了解哪种方式,都在其上记录了多态关联。)>除了有关简单多态关系的信息外,数据透视表上还记录了这种角色。

例如,X既是Post#1的作者又是翻译者,因此有两行具有相同的people_idpeopleable_typepeopleable_id,但是对于role它们具有不同的值。

我正在从“ Laravel ORM”过渡到“ Rails Active Record”,但我找不到您该怎么做:$ this-> people()-> attach($ person ['id'], ['role'=> $ role]);说明...

  1. Rails是“常规配置”。模型”必须为单数“人物”。

  • ActiveRecord具有has_many ...通过和多态关联
  • class Person < ApplicationRecord has_many :assignments, as: :assignable has_many :roles, through: :assignments end class Role < ApplicationRecord has_many :assignments has_many :people, through: :assignments end class Assignment belongs_to :role belongs_to :assignable, polymorphic: true end

    您可以阅读更多Rails has_many :through Polymorphic Association by Sean C Davis
    ruby-on-rails eloquent rails-activerecord polymorphic-associations
    1个回答
    0
    投票
    1. Rails是“常规配置”。模型”必须为单数“人物”。
    © www.soinside.com 2019 - 2024. All rights reserved.