依类型创建和访问has_many

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

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

ChildType有3个条目,当我创建一个新的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 ...

jacod2980 回答:依类型创建和访问has_many

您可以使用accepts_nested_attributes代替回调(您应该更改after_create-> after_save,因为不赞成使用新的rails版本)

如果要访问基于child_type的子代列表:

int cols = 6;
int rows = entry_counter / cols;
double all_data[rows][cols];

for(int row_counter = 0; row_counter < rows; row_counter++) {
    for (int col_counter = 0; col_counter < cols; col_counter++) {
        fscanf(input_file,"%lf\n",&all_data[row_counter][col_counter]);
    }
}

它应按您定义的关联使用

本文链接:https://www.f2er.com/3105149.html

大家都在问