【问题标题】:Rails, how to create, edit, save an attribute that is an combination of related objects?Rails,如何创建,编辑,保存作为相关对象组合的属性?
【发布时间】:2013-11-08 00:03:19
【问题描述】:

假设我有一个Foo 模型。 Foo has_many BarBar 商店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

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

【问题讨论】:

  • 您是否有不接受答案的个人政策?如果是这样,那就太糟糕了。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

这不是更新关联值的常用方法,因此 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    相关资源
    最近更新 更多