说我有一个Foo
模型。 Foo
has_many Bar
。Bar
value
存储Foo
。 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
对象。
例如:
{{1}}
是否有轻松实现上述逻辑的方法?
答案 0 :(得分:0)
这不是更新相关值的常用方法,因此没有标准的方法来执行此操作。然而,根据你的实际需要,编写你的方法并不困难。
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