【问题标题】:dependent create and access a has_many by type依赖按类型创建和访问 has_many
【发布时间】:2019-11-14 05:26:43
【问题描述】:

我有一些模型基本上看起来像:

class Parent < ApplicationRecord
  has_many :children
end

class Child < ApplicationRecord
  belongs_to :parent
  belongs_to :child_type 
end

class ChildType < ApplicationRecord
  has_many :children
end

有 3 个 ChildType 条目,当我创建一个新的 Parent 对象时,我想继续创建依赖的 Child 对象,每个子类型一个。

有没有更简洁的方法来做这件事,而不是:

class Parent < ApplicationRecord
  has_many :children

  after_create :create_children

  private

  def create_children
    ChildType.all.each do |ct|
      children.create(child_type_id: ct.id)
    end
  end
end

这行得通,但我想知道 rails 是否有更清洁的方式来做到这一点。

其次,我还想要父级的快捷方法,以便我可以轻松地按类型访问三个子级:

Parent.find(id).child_type_1 # returns children.where(child_type: { id: 1 }).first

我可以在 Child 上创建一个接受类型参数的作用域,但如果可能的话,我宁愿在父级上有一个方法来加载它,如果有一种干净的方法可以做到这一点。我可以在父级上创建 3 种方法来找到每种类型的合适子级,但这不是超级 DRY...

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-6


    【解决方案1】:

    您可以使用accepts_nested_attributes 代替回调(您应该更改 after_create -> after_save,因为新 Rails 版本已弃用)

    如果您想根据 child_type 访问子列表:

    @child_type = ChildType.find(params[:child_tye_id])
    @child_list = @child_type.children
    

    它应该由您定义的关联使用

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2015-02-18
      • 1970-01-01
      • 2019-10-03
      相关资源
      最近更新 更多