I am looking to duplicate multiple records from a table Book
, and modify certain attributes at the same time, such as giving a new user_id
and a new library_id
.
I have put the following together
@new_data = Book.where(library_id: "xxxxxx").dup.tap { |ele| ele.assign_attributes(user_id: @new_user_id, library_id: @new_library_id) }.save
But i have an error :
NoMethodError (undefined method `assign_attributes' for #<Book::ActiveRecord_Relation:0x000055bed16fd5c0>)
Is there a way to do this please ?
CodePudding user response:
You could do it like this:
@new_data = []
Book.where(library_id: 'xxxxxx').each do |book|
new_book = book.dup
new_book.assign_attributes(user_id: @new_user_id, library_id: @new_library_id)
new_book.save
@new_data << new_book
end
Note: Rails convention dictates that Books
should be singular. I've adjusted it to Book
in this code.