我想制作一個activerecord記錄的副本,更改進程中的單個字段(除了id)。實現這一目標的最簡單方法是什么?我意識到我可以創建一個新記錄,然后遍歷每個字段逐個復制數據 - 但我認為必須有一個更簡單的方法來做到這一點......如: @newrecord=Record.copy(:id) *perhaps?*
3 回答

達令說
TA貢獻1821條經驗 獲得超6個贊
要獲取副本,請使用克?。ɑ騞up for rails 3.1)方法:
# rails < 3.1new_record = old_record.clone#rails >= 3.1new_record = old_record.dup
然后你可以改變你想要的任何字段。
ActiveRecord會覆蓋內置的Object#clone,為您提供一個帶有未分配ID的新記錄(未保存到數據庫)。
請注意,它不會復制關聯,因此如果需要,您必須手動執行此操作。
Rails 3.1 clone是一個淺拷貝,使用dup代替...

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
您可能也喜歡ActiveRecord 3.2 的Amoeba寶石。
在你的情況,你可能想使用的nullify
,regex
或prefix
在配置DSL可用的選項。
它支持的簡單和自動遞歸重復has_one
,has_many
和has_and_belongs_to_many
協會,現場預處理和既能對模型和動態應用了靈活而強大的配置DSL。
請務必查看Amoeba文檔,但使用非常簡單......
只是
gem install amoeba
或添加
gem 'amoeba'
到你的Gemfile
然后將變形蟲塊添加到模型中并dup
像往常一樣運行方法
class Post < ActiveRecord::Base has_many :comments has_and_belongs_to_many :tags amoeba do enable endendclass Comment < ActiveRecord::Base belongs_to :postendclass Tag < ActiveRecord::Base has_and_belongs_to_many :postsendclass PostsController < ActionController def some_method my_post = Post.find(params[:id]) new_post = my_post.dup new_post.save endend
您還可以控制以多種方式復制哪些字段,但是,例如,如果您希望防止注釋被復制但是您想要維護相同的標記,則可以執行以下操作:
class Post < ActiveRecord::Base has_many :comments has_and_belongs_to_many :tags amoeba do exclude_field :comments endend
您還可以預處理字段,以幫助指示前綴和后綴以及正則表達式的唯一性。此外,還有許多選項,因此您可以為您的目的以最易讀的方式編寫:
class Post < ActiveRecord::Base has_many :comments has_and_belongs_to_many :tags amoeba do include_field :tags prepend :title => "Copy of " append :contents => " (copied version)" regex :contents => {:replace => /dog/, :with => "cat"} endend
關聯的遞歸復制很容易,也可以在子模型上啟用變形蟲
class Post < ActiveRecord::Base has_many :comments amoeba do enable endendclass Comment < ActiveRecord::Base belongs_to :post has_many :ratings amoeba do enable endendclass Rating < ActiveRecord::Base belongs_to :commentend
配置DSL有更多選項,因此請務必查看文檔。
請享用!:)
- 3 回答
- 0 關注
- 673 瀏覽
添加回答
舉報
0/150
提交
取消