0

说我有一个Foo模型。一个Foohas_many BarBar商店value。AFoo将多个Bar对象存储为一个combo对象。

例如:

f = Foo.find(2)
f.combo
# combo is essentially Bar.find_by(foo: f).pluck(:value).join(" ")
# I want to be able to easily retrieve (like above)
# create/edit/update
f.combo = "moo cow"
# all related existing Bar objects should be updated, 
# and new additions should be created, 
# and no longer relevant ones should be deleted
f.save
# delete
f.combo = nil
# all related Bar objects should be deleted
f.save

有没有一种方法可以轻松地完成上述逻辑?

4

1 回答 1

0

这不是更新关联值的常用方法,因此 afaik 没有标准的方法来执行此操作。但是,根据您的实际需要编写代码并不难。

class Foo < ActiveRecord::Base
   attr_accessor :combo_values, :combo_set

   after_save :update_combo_values

   def combo=(args)
     @combo_values = args
     @combo_set = true
   end

   def update_combo_values
    return unless @combo_set

    self.bars.destroy_all

    if @combo_values
      @combo_values.split(' ').each do |arg|
        bars.create! value: arg 
      end

      @combo_values = nil
      @combo_set = false
    end
  end
end
于 2013-11-08T00:55:03.103 回答