-1

我有两个模型:

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 回答