ruby大神与菜鸟的代码区别

之前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
 
大神菜鸟高下立判
posted @ 2013-11-25 18:53  wangyuyu  阅读(516)  评论(2编辑  收藏  举报