ruby大神与菜鸟的代码区别

时间:2024-07-06 19:36:14
之前Brand类   has_and_belongs_to_many :categories, index: true
现在在Category类 增加
has_and_belongs_to_many :brands, index: true
实现brand.categories关联的数据 同步到 cagegory.brands
我写的代码:
Brand.each do |brand|
  if brand.categories
    brand.categories.each do |category|
      category.brands << brand
      category.save
    end
  end
end
力哥的代码:
Category.each do |c|
  c.brand_ids = Brand.where(category_ids: c.id).collect(&:id)
  c.save
end
大神菜鸟高下立判