【问题标题】:Duplicate/clone a record and it's associated records复制/克隆记录及其关联记录
【发布时间】:2013-09-19 19:32:09
【问题描述】:
class Game
  has_many :players, dependent: :destroy
end

class Player
  belongs_to :game
end

假设我们有一个游戏和三个与之关联的玩家。

我们如何在不使用任何 gem 的情况下,以最简洁的方式复制这四个记录?

Here are two questions 在 SO 上围绕同一主题,但要么使用宝石,要么看起来过于复杂。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    这段代码可以作为开始:

    class Game
      has_many :players
    
      def clone
        attributes = self.attributes
        ['id', 'created_at', 'updated_at'].each do |ignored_attribute|
          attributes.delete(ignored_attribute)
        end
        clone = Game.create(attributes)
        self.players.each do |player|
          player.clone.update_attributes(game_id: clone.id)
        end
    
        clone
      end
    end
    
    class Player
      belongs_to :game
    
      def clone
        attributes = self.attributes
        ['id', 'created_at', 'updated_at'].each do |ignored_attribute|
          attributes.delete(ignored_attribute)
        end
        clone = Player.create(attributes)
    
        clone
      end
    end
    

    这样,您可以创建一个模块 acts_as_clonable,并将其包含在您的模型中,并提供一些选项:

    class Game
      has_many :players
    
      acts_as_clonable relations: [:players], destroy_original: false, ignored_attributes: [:this_particular_attribute]
    

    如果你有野心,你可以用这个制作宝石...... ;-)

    【讨论】:

    • 不客气,陌生人!啊,您的用户名非常适合这种情况!
    猜你喜欢
    • 1970-01-01
    • 2013-06-05
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2021-01-07
    • 2012-12-23
    相关资源
    最近更新 更多