-1

私は2つのモデルを持っています:

class Song < ActiveRecord::Base
  attr_accessible :title, :singer, :year, :production
end

と:

class SongsCopy < ActiveRecord::Base
  attr_accessible :title, :singer, :year
end

作成A(Song)に属性をコピーする最も簡単な方法は何ですか?属性がないことを覚えていますか?B(SongsCopy) BSongsCopy:production

4

2 に答える 2

3

最適な方法は、データベース内で少し SQL を使用して実行することです。

insert into songs_copies (title, singer, year)
select title, singer, year
from songs
where ...

しかし、実行する必要があるコールバックがたくさんある場合は、次のようにすることができます。

song = some_song_that_you_already_have
copy = SongsCopy.create(song.attributes.except('id', 'production'))

また:

copy = SongsCopy.create(song.attributes.slice('title', 'singer', 'year'))
于 2013-07-07T20:47:08.810 に答える
1

それは最も美しい可能性ではありません (そして確かに好まれません) が、最も簡単な方法は次のとおりです。

class SongsCopy < ActiveRecord::Base
  def initialize(args = nil)
    if args.is_a? Song
      super
      self.title = song.title
      self.singer = song.singer
      self.year = song.year
    else
      super(args)
    end
  end
end

a = Song
b = SongsCopy.new(a)

これを行う別の方法があると確信していますが、上記は機能するはずです。

于 2013-07-07T20:46:46.763 に答える