Rails,如何创建,编辑,保存属于相关对象组合的属性?

时间:2013-11-08 00:03:20

标签: ruby-on-rails ruby activerecord

说我有一个Foo模型。 Foo has_many BarBar value存储FooBar将多个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}}

是否有轻松实现上述逻辑的方法?

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